Spring的@Value注释可以与实现BeanPostProcessor的类型一起使用吗?

时间:2017-03-09 16:46:54

标签: java spring

正如javadoc for @Value

中所述
  

您无法在@ValueBeanPostProcessor类型

中使用BeanFactoryPostProcessor

但它适用于我

@Component("emp")
class Employee implements BeanPostProcessor {
    @Autowired
    public Employee(@Value("pankaj") String name) {
        System.out.println(name);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

这是打印出来的

pankaj

我错过了什么?

我也试过表达,它也有效: 在Employee上面推出的课程

@Autowired
    public Employee(@Value("#{example.name}") String name) {
    System.out.println(name);
    }

示例类就像这样

@Component("example")
public class Example {
    public static String name="Abc";
}

打印出来

Abc

我尝试使用属性解析,它也适用于我: 的 propfolder / abc.properties

  

example.name = pankaj dubey   的 spring.xml

 <context:component-scan base-package="spring.tst.beans"/>
 <context:property-placeholder location="propfolder/abc.properties"/>

使用以下代码更新了Employee课程

@Autowired
    public Employee(@Value("${example.name}") String name) {
    System.out.println(name);
    }

1 个答案:

答案 0 :(得分:1)

javadoc指的是注释的属性解析功能。例如,你可能有

@Value("${example.pankaj}")

您希望Spring使用键example.pankaj(来自某个属性源)注入属性的值。在你的例子中,这不会发生。相反,Spring将注入值

${example.pankaj}

字面上。

相关问题