最近springMVC項目和springboot項目都遇到用@value獲取配置文件中配置項值為空的情況,以下是我的解決方法:
springMVC項目解決方法:
service-context文件中增加下面配置:
<context:component-scan base-package="com.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
以上配置用來掃描項目包名下的所有類
由於我service層和common模塊都需要獲取配置文件中配置項的值,但是添加上面的配置后,我只能在service層通過@value獲取到配置項的值,common模塊仍然無法獲取到配置項的值
注意:如果注解獲取配置文件的值是中文,需要在service-context.xml中自動引入屬性文件添加支持編碼UTF-8格式,如下所示:
<!-- 自動引入屬性文件 -->
<context:property-placeholder location="/conf/*.properties" file-encoding="UTF-8"/>
springboot項目解決方法:
需要在類添加@Component注解
例如:
@Component
public class TestUtil {
public static boolean enable;
@Value("${enable}")
public void setEnable(boolean enable) {
TestUtil.enable = enable;
}
}
注意事項:
1.@value獲取值為null,可能是由於使用static、final修飾變量名:
@Value("${enable}")
public static boolean enable; //獲取值為null
2.一個static修飾的變量需要使用到@value獲取到值的變量,需要添加@PostConstruct
例如:
@Component
public class TestUtil {
public static String url;
@Value("${url}")
public void setEnable(String url) {
TestUtil.url = url;
}
private static String uri;
@PostConstruct
public void init() {
uri = "http://" + uri;
}
}
3.接收變量為int、long類型的值需要如下接收
@Value("#{${bandwidth}}")
public Long bandwidth;