The @AutoWired, @Qualifier, @Resource, and @Value annotations are all used to inject data in the same way that a bean tag is written in an XML configuration file! The special focus of this article is the @Autowired annotation

1. Give a scenario

To start with the @autowired annotation, here’s a scenario:

The dao layer code

@Repository
public class AccountDao {
    public void save() {
        System.out.println("Dao data save succeeded...."); }}Copy the code

The service layer code

@Service
public class AccountImpl implements AccountService {
    
    private AccountDao accountDao;

    @Override
    public voidsave() { accountDao.save(); }}Copy the code

Presentation layer Controller code:

// Simulate a presentation layer function
public class AccountController {
    public static void main(String[] args) {
        //1. Get the core container object
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("Applicationcontext.xml");
        //2. Get the Bean object by id
        AccountService as  = (AccountService)ac.getBean("accountImpl");
        as.save();
        System.out.println(as); }}Copy the code

The results

java.lang.NullPointerException

So why does this exception happen? It is obvious from the code that the service has a null pointer exception for an attribute of type AccountDao that has not been injected, so the @AutoWired annotation comes in….

2, the @autowired

Spring 2.5 has introduced the @AutoWired annotation, which annotates class member variables, methods and constructors, parameters, etc. (again mainly used for variables and methods), for auto-assembly. Eliminate the set, get method by using @Autowired. That is, injecting property data using @Autowired annotations does not require the class to provide a set method. The @Autowired function is the same as writing a < property > tag to the bean tag in an XML configuration file.

How did you use the factory pattern to achieve program decoupling in the previous Spring article? The key is the ID in the bean label, and the value is the class in the corresponding bean label.

@autowired will first skip the key in the IOC container and go directly to the container to find the corresponding attribute! In other words, it has nothing to do with key.

Autowired Three cases of automatic assembly:

If a unique bean object type matches the @autoWired variable type, the injection succeeds! None of the bean object types in the container match the type of the variable modified by @autoWired. 3. If there are multiple bean object types in the container that match the variable type modified by @AutoWired, search for the variable name modified by @AutoWired, and inject successfully if found.

Many people will ignore or not understand the third point!!

3, @ the Qualifier

In the third case of @autowired above, the variable name needs to be changed to correspond to the injection, which is not very flexible for the program, hence the @qualifier annotation. The @qualifier is used to inject by name in addition to injection by class. It cannot be used independently when injecting class members (but can be used independently when injecting method parameters), so the @qualifier annotation is limited and is not used very much. The @qualifier is often used in combination with @autoWired to indicate auto-assembly of specific names


    @Autowired // If there is only one @autowired annotation, it will look for IAccuntDao. If there are two IAccuntDao annotations, it will match IAccuntDao and accountDao.
    @Qualifier("accountDao2") // Add this annotation to find IAccuntDao with the name accountDao2private IAccuntDao accountDao; So this code annotation is simply looking for a component of type IAccuntDao with the name accountDaoCopy the code

In fact, the above annotation is equivalent to the following annotation, which we will discuss later:

 @Resource("accountDao2")
 private IAccuntDao accountDao;
Copy the code

4, @ the Resource

@resource is provided by J2EE, and is automatically injected byName by default. @resource has two important attributes, name and type, and the default is name. It’s better to use @autoWired, so for @Resource just remember to auto-inject by name

5. The difference between @autowired and @Resource

I have to say that these two annotations are very similar and can easily be confused.

The main differences between @autowired and @Resource are as follows:

@Autowired @Resource
Annotation provider Spring J2EE
Automatic assembly mode attribute The name

In fact, the main difference is this one or two points, of course, there must be details, here is not outlined temporarily.

One important point, of course, is that @resource equals @autowired + @Qualifier

6, @ the Value

Since @AutoWired, @Qualifier, and @Resource autowiring can only be used to inject data of other bean types, primitive types and String types cannot be implemented using the above annotations. Hence the @value annotation, which is specifically used to serve primitive and String types.

In addition, the @value annotation has a Value attribute that specifies the Value of the data. It can use spring’s SpEL(that is, spring’s EL expression). SpEL = ${expression}; mybatis = #{expression}

@Value("# {2 * 3}")  //# = 6
private int age;

@Value("178")    // 178
private int height;

@Value("${man.weight}")  //SpEL operates on data in the configuration file
private int weight;
Copy the code

Note: Injection of collection types can only be done through XML

7, summary

The @AutoWired, @Qualifier, @Resource, and @Value annotations above are all used to inject data in the same way that a bean tag is written in an XML configuration file!

If this article helped you a little bit, please give it a thumbs up. Your approval is my biggest motivation. Thank you

Finally, if there is insufficient or improper place, welcome to criticize, grateful! If you have any questions welcome to leave a message, absolutely the first time reply!

Welcome to pay attention to my public number, there are some Java learning materials and a large wave of Java electronic books, such as Zhou Zhiming teacher’s in-depth Java virtual machine, Java programming thought, core technology volume, big talk design mode, Java concurrent programming combat….. Are Java bible, don’t say fast on the Tomcat car, how we go! The most important is to discuss technology together, yearning for technology, the pursuit of technology, good come is a friend oh…