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

本文介绍了一种在Spring Boot项目中解决属性注入失败的方法。通过在配置类中引入PropertySourcesPlaceholderConfigurer,成功从application.yml中读取了配置项。文中还提供了具体的实现代码和解决步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

在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

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值