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

问题:

在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 aFileHandler = 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

posted @ 2018-01-19 11:12  hongweigg  阅读(167)  评论(0编辑  收藏  举报