1

For automatic injection, @Autowired is enough, why use @Value. I think it maybe ambiguous and semantic inconsistency. see AutowiredAnnotationBeanPostProcessor.

I have to emphasize that the function of @Autowired and @Value is equivalent for AutowiredAnnotationBeanPostProcessor. Refer to the following code, They all implement injection functions.

@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.
    }
}

the placeholder function for @Value is supported by PropertySourcesPlaceholderConfigurer other than AutowiredAnnotationBeanPostProcessor.

peacetrue
  • 186
  • 1
  • 15
  • duplicate of https://stackoverflow.com/questions/29551761/spring-value-vs-autowired ? – Jayesh Sep 01 '18 at 03:28
  • @Jayesh Obviously not repeated, the link explain the difference between value and autowired, but my question is focus on AutowiredAnnotationBeanPostProcessor, For AutowiredAnnotationBeanPostProcessor, the functions of Autowired and Value are equivalent. – peacetrue Sep 01 '18 at 04:51

1 Answers1

0

@Autowired is a spring propriety annotation that inject a resource by type, i.e. by corresponding implemented class (annotated with @Component) to afield annotated with @Autowired. Fundamentally, @Autowired is about type-driven injection.

@Autowired
private OrderService orderService;

while,

@Value annotation is used to assign a value to a property. It is only used to assign a value for a simple type property,for example, primitive types, in a bean class.in this way, IOC container reads the value of a key from resource bundle and initializes a simple property with that value.

@Value("#{mysql.databaseName}")
private String databaseName;

In reference to the the above definitions, the difference is clear as you can not assign simple type values using @Autowire. similarly, you also can not inject a complex type (i.e. class) by @Value so the usages are not the same