@Value未注入 [英] @Value is not injected

查看:256
本文介绍了@Value未注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试将属性文件中的值注入到spring配置类中,如下所示:

I'm trying to inject value from properties file into a spring configuration class as follows:

@Configuration
@EnableWebMvc
public class ImagesContext {
   @Autowired
   @Value("${some.property.com}")
   private String property;

   @Bean
   public MyClass getMyClass() {
      return new MyClass(property);
   }
}

但是该属性未正确注入.相反,在调试时,我看到property字符串包含${some.property.com}而不是字符串值本身.

But the property is not injected correctly. Instead, when I debug, I see that the property string contains ${some.property.com} and not the string value itself.

推荐答案

@Value注释由AutowiredAnnotationBeanPostProcessor处理,如果您在XML中具有<component-scan><annotation-config>配置(或直接使用<component-scan><annotation-config>配置),通常会注册该注释. bean定义).您需要添加其中任何一个,可能是<annotation-config>

The @Value annotation is processed by AutowiredAnnotationBeanPostProcessor which is typically registered if you have a <component-scan> or <annotation-config> configuration in XML (or directly with a bean definition). You need to add either of those, probably <annotation-config>

如果尚未在Config类中添加以下bean声明

Add the following bean declaration in your Config class if not done already

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

为使@Value注释起作用,应注册PropertySourcesPlaceholderConfigurer.在XML中使用<context:property-placeholder>时会自动完成,但是在使用@Configuration时应将其注册为静态@Bean.

In order for @Value annotations to work PropertySourcesPlaceholderConfigurer should be registered. It is done automatically when using <context:property-placeholder> in XML, but should be registered as a static @Bean when using @Configuration.

这篇关于@Value未注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆