preface

In the previous article, we registered the Bean with the Spring container using the @Bean(or @Component) annotation; The purpose of creating these beans is, ultimately, to use the @AutoWired annotation to automatically inject beans into class properties. The @AutoWired annotation, which can be annotated directly on properties, constructors, methods, or even incoming parameters, essentially calls setter method injection.

The source code

Source Code: 
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required(a) default true;
}
Copy the code

Spring reports an error when the auto-injected Bean does not exist; If you want to inject while the Bean exists, you can use @AutoWired (Required =false).

use

To mark on an attribute:

.@Autowired
privateMyBean myBean; .Copy the code

Marked in the method:

.@Autowired
public void setMyBean(MyBean myBean) {
    this.myBean = myBean; }...Copy the code

Annotated on the constructor:

.@Autowired
public MyClass(MyBean myBean) {
    this.myBean = myBean; }...Copy the code

Marked on method parameters:

.public void setMyBean(@Autowired MyBean myBean) {
    this.myBean = myBean; }...Copy the code

added

  1. @Autowiredand@ResourceAnnotations are used as bean object injection,@AutowiredAre annotations provided by Spring, and@ResourceIt is provided by J2EE itself.
  2. @AutowiredThe injected object is first found by type, and then matched by name if there are more than one.
  3. If the name is not distinguishable, you can pass@QulifierExplicitly specify, for example:
@Autowired
@Qualifier("userServiceImpl1")
private UserService userService;
Copy the code