您的位置:首页 > 移动开发

Springboot 配置类( @Configuration) 不能使用@Value注解从application.yml中加载值

2018-01-19 11:12 726 查看
问题:
在Springboot应用中,通过Spring-context(版本4.3.6)的@Configuration注解配置类,使用@Value注解从application.yml配置文件中加载属性,但是总是报找不到,设置缺省值,则获取到的值总是缺省值。
1、Configuration文件

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ADemoConfiguration {
static Logger log = LoggerFactory.getLogger(ADemoConfiguration.class);

public ADemoConfiguration(){
log.info("Here ADemoConfiguration init...");
}

@Value("${yy.a.disabled:false}")
boolean disableA;

@Value("${eureka.client.serviceUrl.defaultZone:nothing}")
String defaultZone;

@Bean
AFileHandler aFileHandler(LoginHandlerHessianNoAuth auth) throws Exception{
AFileHandler udsFileHandler = new AFileHandler();
log.info("disableA:" + disableA + ",defaultZone:" + defaultZone);

aFileHandler.setDisabled(disableA);
aFileHandler.setClientConfigInfo(clientConfigInfo());
aFileHandler.setLoginHandler(auth);

return aFileHandler;
}2、yml文件yy:
a:
disabled: true
eureka:
client:
enabled: true
serviceUrl:
defaultZone: http://localhost:7070/eureka/解决:在配置文件ADemoConfiguration中加入: @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}PropertySourcesPlaceholderConfigurer位置:
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
重新编译后,发现问题解决。
参考:
1、Spring @Value is not resolving to value from property file. https://stackoverflow.com/questions/15937592/spring-value-is-not-resolving-to-value-from-property-file
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息