在controller中无法通过注解@Value获取到配置文件中定义的值解决办法

使用springMVC的朋友,有时候可能会遇到以下问题:

想在controller中使用@Value指定变量,但是无法得到对应的值。而在server层获取,是正常的。
解决方案:
1:在srping-mvc.xml 加上以下配置。相当于在springmvc配置文件中也读取properties文件,这样controller就访问自己容器中的数据
<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" />
2:在父容器中注册一个公用Bean,然后把配置文件的值注入到这个Bean中

因为Service层的对象是有Spring容器创建,因此我们定义一个Component: AccOauthUtils,注入进来属性用public修饰

@Component
public class AccOauthUtils {

@Value("${accStatus}")
public String accStatus;

在controller注入(必须通过@Autowired注解,通过new AccOauthUtils的形式无法获取值):

@Autowired
private AccOauthUtils accOauthUtils;

再通过 accOauthUtils.accStatus获取

猜你喜欢

转载自blog.51cto.com/1008610086/2376574