前阵子有个新的需求,需要在Spring Boot项目里面新增一个配置文件,因为配置项很多,所以也不好直接添加在之前已有的application.properties里面,需要单独另加一个新的配置文件,现在需要在项目里面能够读取到这个新加的配置文件的配置项内容,用了很多方法直接用@Value注解或者直接在需要用到的地方使用Environment都不行,最后是采用如下方式解决的:
新增的配置文件结构如图
代码的话是新建一个如下所示的配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* 国际化配置
*
* @author 31777
* @version Ver 1.0
* @since Ver 1.0
* @Date 2018年3月21日
*
*/
@Component
@Configuration
@PropertySource("classpath:config/messageResource_en.properties")
public class LocaleConfig {
@Autowired
private Environment env;
public Environment getEnv() {
return env;
}
public void setEnv(Environment env) {
this.env = env;
}
}
@Component标识为Bean
@Configuration表明这是一个配置类
@PropertySource("classpath:****")标明配置文件路径
接着在需要使用的地方直接注入并获取就能使用了:
@Autowired
private LocaleConfig localeConfig;
******{
******
localeConfig.getEnv().getProperty("需要的配置项");
*******
}