[Spring] IOC core container and XML management Bean

1, IOC (control reversal)

Dependency Injection (DI) has the same meaning as control inversion (Ioc), but the same concept is described from different angles.
1. Inversion of control (IoC): leave the creation and calling of objects to Spring for management;
(1) IoC purpose: reduce coupling
(2) IoC underlying principles: xml parsing, factory schema, reflection
2. Dependency injection: from the perspective of the Spring container, the Spring container is responsible for assigning the dependent object to the caller's member variable, which is equivalent to injecting its dependent instance, which is dependency injection;
3.Spring provides two ways (interfaces) to implement IOC:
(1) Bean factory: the factory that manages beans. It is mainly responsible for initializing various beans and calling their life cycle methods; (just understand)
Note: the object will not be created when the configuration file is loaded, but only when the object is obtained (used).

BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("F:/applicationContext.xml"));//Absolute path

(2) ApplicationContext: it is a sub interface of BeanFactory, called application context. Based on all functions of BeanFactory, it also provides support for internationalization, resource access, transaction propagation, etc.
Note: objects in the configuration file will be created when the configuration file is loaded.
ApplicationContext is an interface and cannot be instantiated. The following two methods are usually used to create an instance:
① Created through ClassPathXmlApplicationContext
(the configLocation parameter is used to specify the name and location of the Spring configuration file. If its value is "applicationContext.xml", Spring will find the configuration file with this name from the classpath)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(String configLocation);//Classpath

② Created by FileSystemXmlApplicationContext
(FileSystemXmlApplicationContext will find the specified XML configuration file from the specified file system path (absolute path), find and load the instantiation of ApplicationContext. Using absolute path will lead to poor flexibility of the program and is not recommended.)

ApplicationContext applicationContext1 = new FileSystemXmlApplicationContext(String configLocation);//Absolute path

After the Spring container is created, you can use Spring to obtain Bean instances, as follows:

① Object getBean(String name): obtain the specified Bean according to the id or name of the Bean in the container. After obtaining, forced type conversion is required;
② T getBean(Class requiredType): obtain an instance of a Bean according to the type of the class. This method is generic and does not require forced type conversion.

2, Bean management

Bean management includes operations: creating objects and injecting attributes

Method 1: manage beans in XML mode

Common attributes and child elements of < bean > element
id: the unique identifier of the bean, which is equivalent to alias;
Class: Specifies the specific implementation class of the bean, using the fully qualified name of the class (package class path);
Property: the child element of < bean >, which is used to call the setter method in the bean instance to complete property assignment, so as to complete dependency injection. The name attribute of the element specifies the attribute name in the bean instance, and the ref attribute or value attribute is used to specify the parameter value;
Constructor Arg: the sub element of the < bean > element, which is used to complete dependency injection when the constructor is instantiated;

1. Creating objects in XML

Use the < bean > tag in the Spring configuration file to implement object creation:
When creating an object, the bean's parameterless construction method is used by default;
If you do not specify id and name, Spring uses the class value as an id.

<!--use id Attribute definition bean,The corresponding implementation class is com.jd.wds.Bean1-->
<bean id="bean1" class="com.jd.wds.Bean1"></bean>
<!--use id Attribute definition bean,The corresponding implementation class is com.jd.wds.Bean2-->
<bean name="bean2" class="com.jd.wds.Bean2"></bean>

2. Attribute injection in XML mode

(1) DI (dependency injection): is the injection attribute
Method 1: inject with property setter method
① Create a class and define properties and corresponding setter methods

public class UserDao {
    private int age;
    private String name;
    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void say(){
        System.out.println(name+"::"+age);
    }
}

② Configure ApplicationContext in Spring Create objects and configure attribute injection in XML files

<!--establish id by userDao The implementation class is com.jd.dao.UserDao-->
<bean id = "userDao" class="com.jd.dao.UserDao">
        <!--take name Note for Naza's attributes userDao Instance-->
        <property name="name" value="Naza"/>
        <!--take age Note for the attribute of 19 userDao Instance-->
        <property name="age" value="19"/>
</bean>

Test:

//The attribute setter method implements dependency injection
@Test
public void userDaoTest(){
    //1. Initialize the Spring container and load the configuration file
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //2. Get the instance of UserDao through the Spring container
    UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    System.out.println(userDao);
    //3. Call the say() method in the instance
    userDao.say();
}


Mode 2: injection using a parametric constructor
Constructor injection uses the constructor with parameters to complete attribute injection
① Create a class, define attributes and corresponding parameterized constructors

public class Order {
    private String name;
    private int price;
    public Order() {
    }
    public Order(String name, int price) {
        this.name = name;
        this.price = price;
    }
   public void show(){
       System.out.println("name = "+name+", price = "+price);
   }
}

② Configure ApplicationContext in Spring Create objects and configure attribute injection in XML files

<bean id = "order" class="com.jd.dao.Order">
        <!--take name Note for Naza's attributes userDao Instance-->
        <constructor-arg name="name" value="Apple 13"/>
        <constructor-arg name="price" value="8000"/>
</bean>

Test:

//Constructor implements attribute dependency injection
@Test
public void orderTest(){
    //1. Initialize the Spring container and load the configuration file
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //2. Obtain the instance of Order through the Spring container
    Order order = (Order) applicationContext.getBean("order");
    System.out.println(order);
    //3. Call the say() method in the instance
    order.show();
}


Special case of XML injection:
① The property to be injected contains null values: < property name = "property name" > < null > < / null > < / property >
② The attributes to be injected contain special symbols: < property name = "name" > < value > <! [CDATA [Special]] > < / value > < / property >

Special case of injecting attributes

(1) Inject external bean s
Configuration file beans xml

<bean id="userService" class="com.jd.ioc.Impl.UserServiceImpl">
	<!--take id by userDao Examples of note userService In an instance of-->
    <property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.jd.ioc.Impl.UserDaoImpl"></bean>

(2) Injecting internal bean s and cascading assignments
Configuration file beans1 xml

<bean id="employee" class="com.jd.dao.Employee">
    <!--Set two common properties of injection-->
    <property name="name" value="Xiao Wang"></property>
    <property name="sex" value="female"></property>
    <!--inside Bean,Set injection object properties-->
    <property name="dept">
        <bean id="dept" class="com.jd.dao.Dept">
            <property name="dName" value="Ministry of Personnel"></property>
        </bean>
    </property>
 </bean>

Cascade assignment beans xml

<bean id="employee" class="com.jd.dao.Employee">
    <!--Set two common properties of injection-->
    <property name="name" value="Xiao Wang"></property>
    <property name="sex" value="female"></property>
    <!--Cascade assignment-->
    <property name="dept" ref="dept"></property>
 </bean>
<bean id="dept" class="com.jd.dao.Dept">
    <property name="dName" value="Finance Department"></property>
</bean>

(3) Inject properties of collection type
Configuration file beans4 xml

<bean id="student" class="com.jd.dao.Student">
    <property name="array">
        <array>
            <value>"Beijing"</value>
            <value>"Nanjing"</value>
        </array>
    </property>
    <property name="list">
        <list>
            <value>"Java Basics"</value>
            <value>"data structure"</value>
        </list>
    </property>
    <property name="map">
        <map>
            <entry key="chinese" value="Mandarin"></entry>
            <entry key="English" value="Foreign Languages"></entry>
        </map>
    </property>    
</bean>

1. Spring has two types of beans, a normal bean and a factory bean
2. Ordinary bean: the bean type defined in the configuration file is the return type
3. Factory bean: the bean type defined in the configuration file can be different from the return type
The first step is to create a class that acts as a factory bean and implements the interface FactoryBean;
The second step is to implement the method in the interface and define the returned bean type in the implemented method

Keywords: Spring xml Container

Added by thryb on Thu, 16 Dec 2021 00:11:36 +0200