@Value未注入

Avi*_*Avi 5 spring properties code-injection

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

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

   @Bean
   public MyClass getMyClass() {
      return new MyClass(property);
   }
}
Run Code Online (Sandbox Code Playgroud)

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

Ank*_*hal 13

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

如果尚未完成,请在Config类中添加以下bean声明

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
Run Code Online (Sandbox Code Playgroud)

为了使@Value注释工作,PropertySourcesPlaceholderConfigurer应该注册.它使用时自动完成<context:property-placeholder>的XML,而应该当作静态@Bean使用时@Configuration.