为什么AutowiredAnnotationBeanPostProcessor支持@Value?

时间:2018-09-01 03:22:14

标签: java spring

对于自动注入,@Autowired就足够了,为什么要使用@Value。我认为这可能是模棱两可的,而且语义上也不一致。 参见AutowiredAnnotationBeanPostProcessor

我必须强调@Autowired@Value的功能等效于AutowiredAnnotationBeanPostProcessor。请参考以下代码,它们都实现注入功能。

@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
    this.autowiredAnnotationTypes.add(Autowired.class);
    this.autowiredAnnotationTypes.add(Value.class);
    try {
        this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
        logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
    }
    catch (ClassNotFoundException ex) {
        // JSR-330 API not available - simply skip.
    }
}

@Value而非PropertySourcesPlaceholderConfigurer支持AutowiredAnnotationBeanPostProcessor的占位符功能。

1 个答案:

答案 0 :(得分:0)

  

@Autowired 是一个春季专有注释,它按类型 注入资源,即按相应的实现类(用@Component注释)注入到用@Autowired注释的字段。从根本上讲   @Autowired与类型驱动注入有关。

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    dataGridView1.CurrentCell = null;
}

同时

  

@Value 批注用于为属性分配 value 。它仅用于为简单类型属性分配值,例如,   Bean类中的基本类型。以这种方式,IOC容器读取了   资源包中的的值并初始化一个简单的   具有该值的属性。

@Autowired
private OrderService orderService;

参考以上定义,区别很明显,因为您不能使用@Autowire分配简单类型值。同样,您也无法通过@Value 注入复杂类型(即类),因此用法不同