How does Java automatically inject bean using @ Autowired annotations

  • 2021-09-20 20:19:32
  • OfStack

Java @ Autowired annotation automatically injects bean

annotationWire. xml (1 remember to configure context: annotation-config/)


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <bean id="order" class="com.annotationWire.pojo.Order" p:order="202020124546" />
    <bean id="user" class="com.annotationWire.pojo.User" />
</beans>

Class User


package com.annotationWire.pojo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
@Data
public class User {
    private String name;
    @Autowired
    private Order order;
}

Class Order


package com.annotationWire.pojo;
import lombok.Data;
@Data
public class Order {
    private String order;
}

Test class


package com.annotationWire;
import com.annotationWire.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnnotation {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("annotationWire.xml");
        User student = applicationContext.getBean(User.class);
        System.out.println(student);
    }
}

java configures spring, unable to automatically inject bean @ Autowired

To add @ ComponentScan to the configuration class

The objects of scan are different on both RootConfigure and ServletConfig classes

ServletConfig is used to register DispatcherServlet, and it is only used to scan controller layer

RootConfigure is used to register ContextLoaderListener, and it scans bean other than controller, such as dao, service and bean entities.


Related articles: