Home > Enterprise >  Why @Autowired still works while @Bean annotation's autowire property default value is Autowire
Why @Autowired still works while @Bean annotation's autowire property default value is Autowire

Time:01-30

Here is the @Bean source code:

    @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Bean {
        @AliasFor("name")
        String[] value() default {};
    
        @AliasFor("value")
        String[] name() default {};
    
        Autowire autowire() default Autowire.NO;
    
        String initMethod() default "";
    
        String destroyMethod() default "(inferred)";
    }

I find that autowire's default value is Autowire.NO, but when I use this bean with @Autowired it still works, is it behavior by default or by some kind of convention?

CodePudding user response:

From the documentation:

public abstract org.springframework.beans.factory.annotation.Autowire autowire Are dependencies to be injected via convention-based autowiring by name or type? Note that this autowire mode is just about externally driven autowiring based on bean property setter methods by convention, analogous to XML bean definitions.

The default mode does allow for annotation-driven autowiring. "no" refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses through annotations. See Also:

Autowire.BY_NAME, Autowire.BY_TYPE Default: org.springframework.beans.factory.annotation.Autowire.NO

In other words, that property has nothing to do with how your bean is injected into other beans, but how the bean's own properties are implicitly autowired.

By default (Autowire.NO) means that Spring will not attempt to call setter methods unless annotated with @Autowired explicitly

This was also answered here

  • Related