SpringBoot读取配置文件并注入到常量中

1 读取配置文件到常量中

大家熟知的方式是将配置文件注入到一个bean中去访问,但是这种方式每次使用这个bean都要写一个注入@Autowired去引用这个bean不是很方便,如果将配置文件注入到一个配置常量用,那么每次访问用Constant.NAME就可以了,这样是不是方便了很多

package com.pibigstar.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 常量
 * @author pibigstar
 *
 */
@Configuration
public class Constant {
    //此数据是读取的配置文件
    public static String DEFAULT_FILE_UPLOAD_PATH;
    //注入
     @Autowired(required = false)
     public void setUploadPath(@Value("${parsevip.file.path}")String DEFAULT_FILE_UPLOAD_PATH) {
         Constant.DEFAULT_FILE_UPLOAD_PATH = DEFAULT_FILE_UPLOAD_PATH;
     }

}

配置文件application.yml中:

parsevip:
  file:
    path: D://upload/

使用

//任意处
String filePath = Constant.DEFAULT_FILE_UPLOAD_PATH;

2 读取自定义的配置文件

那我们可不可以读取自定义的配置文件呢,答案是肯定的,看代码

package com.pibigstar.common.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 读取配置文件的自定义常量
 * @author pibigstar
 *
 */
@Configuration
@PropertySource("classpath:myconfig.properties")
@ConfigurationProperties(prefix="parsevip")
public class MyConfiguration {

    private String filePath;

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

}

使用:

    @Autowired
    private MyConfiguration myConfig;

myconfig.properties (将此文件放到src/main/resources目录下)

parsevip.filePath=D://temp

有一点要注意:用此方法必须为*.properties 文件,不能是yml文件,不知道yml文件应该怎么读取,有知道的麻烦留言告诉我一声,不胜感激。。。。

猜你喜欢

转载自blog.csdn.net/junmoxi/article/details/80817107