Please go to DobbyKim’s Question of the Day for more questions

A:

First of all, the similarities between them are as follows:

The @autoWired and @Resource annotations can both be used to assemble beans; And, both can be written on fields or setter methods.

Differences between the two:

  1. The @autowired annotation is provided by the Spring framework, and @ Resource annotation is javax.mail. The annotation. Provided the Resource, which is the J2EE standard, but Spring supports the annotations inject beans.

  2. The @autoWired annotation default assembles dependent beans by Bean type (byType). By default, it requires that the dependent object must exist. Null values are not allowed by default. You can set its required property to false. The most common problem is that the mapper interface of Mybatis uses @autowired to introduce an error message:

    In this case, setting the required attribute to false solves the problem

    The @Resource annotation defaults to assembling dependent beans by Bean name (byName). The @resource has two important attributes, name and type. The @resource assembly Bean principle:

    • If the name and type attributes are not specified, the assembly is byName by default
    • If both the name and type attributes are specified, assemble a Bean from the Spring context that uniquely matches both the name and type, and throw an exception if none is found
    • If only the name attribute is specified, the Bean with a matching name is searched from the Spring context for assembly, and an exception is thrown if it does not find one
    • If only the type attribute is specified, the Spring context will look for a unique Bean that matches the type and assemble it, throwing an exception if it finds none or more than one

Since we mentioned the @qualifier annotation above, let’s look at its basic usage.

The @qualifier annotation specifies which beans should be automatically injected. This annotation helps to disambiguously inject beans automatically, for example:

MyService

public interface MyService{ 
	// ...
}
Copy the code

MyServiceImpl1

@Service
public class MyServiceImpl1 implements MyService {
  // ...
}
Copy the code

MyServiceImpl2

@Service
public class MyServiceImpl2 implements MyService {
  // ...
}
Copy the code

When we injected MyService in the Controller, there were two implementation classes for MyService, so we should use the @qualifier annotation to specify which implementation class should be injected:

@Controller
public class MyController {
	@Autowired
    @Qualifier("MyServiceImpl1") // Specify MyServiceImpl1 should be injected
    private MyService myService;
    
    // ...
}
Copy the code

Another common practice for @qualifier is to have the @AutoWired annotation assemble objects according to byName, as shown in the following example:

public class Test {
	@Autowired
	@Qualifier("userDao")
	private UserDao userDao;
	// ...
}
Copy the code