Spring Framework - IOC Assembly Bean

Keywords: Java xml Spring Attribute

IOC Assembly Bean

(1) The Spring Framework Bean instantiation approach provides three ways to instantiate beans
Constructor instantiation (default parameter-free, most used)
Static factory instantiation
Instance factory

Let's start with the application Context. XML configuration files for these three methods:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
 6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 8        
 9     <!-- Bean Three ways of instantiation================================================================================ -->    
10       <!-- 2.1  Using a parametric-free constructor -->
11      <bean id="bean1" class="com.study.spring.b_instance.Bean1"></bean>
12       <!-- 2.2 Using static factory method  factory-method It is the static method provided by the factory. -->
13      <bean id="bean2" class="com.study.spring.b_instance.Bean2" factory-method="createInstance"></bean>
14      <!-- 2.3 Method of Configuring Instance Chemical Plant -->
15      <bean id="bean3Factory" class="com.study.spring.b_instance.Bean3Factory"></bean>
16      <bean id="bean3" factory-bean="bean3Factory" factory-method="getInstance"></bean>
17     <!-- end.Bean Three ways of instantiation================================================================================ -->    
Class Bean1
public class Bean1 {
    
    //A parametric constructor system must be provided with default parametric constructors
}
Class Bean2
public class Bean2 {
    private static Bean2 Bean2 = new Bean2();

    private Bean2() {
    }

    public static Bean2 createInstance() {
        return Bean2;
    }
}

Class Bean3

public class Bean3 {

}

Bean3Factory class

 1 public class Bean3Factory {
 2     
 3     private Bean3Factory(){
 4         
 5     }
 6       
 7     public Bean3 getInstance(){
 8         return new Bean3();
 9     }
10 }

Test class InstanceDemo

 1 import org.junit.Test;
 2 import org.springframework.context.ApplicationContext;
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 public class InstanceDemo {
 6     
 7     //Case Chemical Plant Method
 8     @Test
 9     public void demo3(){
10        //Load configuration files to create factories
11         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
12         
13         Bean3 bean3 =(Bean3) applicationContext.getBean("bean3");
14         System.out.println(bean3);
15         
16     }
17     
18     //Static Factory Method
19     @Test
20     public void demo2(){
21        //Load configuration files to create factories
22         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
23         
24         Bean2 bean2 =(Bean2) applicationContext.getBean("bean2");
25         System.out.println(bean2);
26         
27     }
28     //Construction method bean object
29     @Test
30     public void demo1(){
31        //Load configuration files to create factories
32         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
33         
34         Bean1 bean1 =(Bean1) applicationContext.getBean("bean1");
35         System.out.println(bean1);
36         
37     }
38 }
39 /*
40  * All three have memory addresses similar to com.study.spring.b_instance.Bean1@7229c204
41  */

(2) Other configurations of Beans:

In general, when assembling a Bean, the name of the Bean is specified by specifying an id attribute

The id attribute must be unique in the IoC container

To satisfy the XML naming specification for ID attributes, the name of ID must start with letters, using letters, numbers, hyphens, underscores, sentences, colons

If the Bean name contains special characters, you need to use the name attribute such as <Bean name=" person" class="cn.itcast.Bean.Person"/>.

Since the name attribute can be the same, subsequent occurrences of beans override previous occurrences of beans with the same name

The difference between id and name:

id complies with the id constraints of XML constraints. id constraints ensure that the value of this attribute is unique and must start with letters, using letters, numbers, hyphens, underscores, sentences, colons

name does not have these requirements

If no id is configured on the bean tag, name can be used as id.

Bean's scope attribute

  <!-- 3.Bean Of scope attribute===================================================================== -->    
     <bean id="product" class="com.study.spring.c_scope.Product" scope="singleton"></bean>
  <!-- end.Bean Of scope attribute===================================================================== -->    

* singleton: singleton. (default value.)

* prototype: Multiple examples.

* request: In web development, an object is created and stored in the request scope, request.setAttribute();

* session: In web development, an object is created and stored in session scope, session.setAttribute();

* globalSession: Generally used in Porlet application environment. It refers to distributed development. It's not a porlet environment. globalSession is equivalent to session.

3. Dependency Injection of Bean Attributes

Now that we know how to get an object, we need to know how to assign attributes to the object.

The following is illustrated by examples:

public class Car {

    private String name;

    private double price;

    public Car(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }
}
Class Car
public class Car2 {
    private String name;

    private double price;

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car2 [name=" + name + ", price=" + price + "]";
    }

}
Class Car2
public class CarInfo {
    
    public String getName(){
        return "Haff H6";
    }
    
    public double caculatePrice(){
        return 110000;
    }
}
Class CarInfo
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class CollectionBean {
    private String name;

    private Integer age;

    private List<String> hobbies;

    private Set<Integer> numbers;

    private Map<String, String> map;

    private Properties properties;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Set<Integer> getNumbers() {
        return numbers;
    }

    public void setNumbers(Set<Integer> numbers) {
        this.numbers = numbers;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "CollectionBean [name=" + name + ", age=" + age + ", hobbies=" + hobbies + ", numbers=" + numbers
                + ", map=" + map + ", properties=" + properties + "]";
    }
    
}
CollectionBean class
public class Employee {

    private String name;

    private Car2 car2;

    public void setName(String name) {
        this.name = name;
    }

    public void setCar2(Car2 car2) {
        this.car2 = car2;
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", car2=" + car2 + "]";
    }

}
Class Employee
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDi {
    
    @Test
    public void demo6() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");

        System.out.println(collectionBean);
    }
    
    
    @Test
    public void demo5() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Car2 car2 = (Car2) applicationContext.getBean("car2_2");

        System.out.println(car2);
    }
    
    
    @Test
    public void demo4() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Employee e = (Employee) applicationContext.getBean("employee2");

        System.out.println(e);
    }
    
    @Test
    public void demo3() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Employee e = (Employee) applicationContext.getBean("employee");

        System.out.println(e);
    }

    @Test
    public void demo2() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Car2 car2 = (Car2) applicationContext.getBean("car2");

        System.out.println(car2);
    }

    @Test
    public void demo1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Car car = (Car) applicationContext.getBean("car");

        System.out.println(car);
    }
}
TestDi test class
Neither of these classes is the most important. We mainly look at how to write the configuration file. This is the most critical:

applicationContext.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
 6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 8     
 9     
10     <!-- Bean Dependency Injection===================================================================================== -->    
11      <!-- 4.1 Constructor Injection -->
12         <bean id="car" class="com.study.spring.e_di.Car">
13             <!-- One way.According to the location of the index -->
14             <!-- <constructor-arg index="0" value="Porsche"></constructor-arg>
15              <constructor-arg index="1" value="1500000"></constructor-arg> -->
16              <!-- Mode two.Configuration by name -->
17              <!-- <constructor-arg name="name" value="BMW"></constructor-arg>
18              <constructor-arg name="price" value="500000"></constructor-arg> -->
19              <!-- Mode three.Configuration by type -->
20              <constructor-arg type="java.lang.String" value="Benz"></constructor-arg>
21              <constructor-arg type="double" value="600000"></constructor-arg>
22         </bean>
23         
24       <!-- 4.2setter Method injection -->  
25       <bean id="car2" class="com.study.spring.e_di.Car2">
26           <property name="name" value="Chevrolet"></property>
27           <property name="price" value="100000"></property>
28       </bean>
29       
30       <bean id="employee" class="com.study.spring.e_di.Employee">
31           <property name="name" value="Zhang San"></property>
32           <property name="car2" ref="car2"></property>
33       </bean>
34       
35       <!-- Quote p Namespace --><!-- If you want to quote p Name, that's at the top sxd To configure  xmlns:p="http://www.springframework.org/schema/p"-->
36        <bean id="car22" class="com.study.spring.e_di.Car2" p:name="BMW" p:price="500000">
37       </bean>
38       <bean id="employee2" class="com.study.spring.e_di.Employee" p:name="Li Si" p:car2-ref="car22"></bean>
39       
40         <!-- Introduce spEL Expression -->
41       <bean id="carInfo" class="com.study.spring.e_di.CarInfo"></bean>
42         <bean id="car2_2" class="com.study.spring.e_di.Car2">
43             <property name="name" value="#{carInfo.name}"></property>
44             <property name="price" value="#{carInfo.caculatePrice()}"></property>
45         </bean>
46         
47      <!-- Dependency Injection of Complex Attributes -->    
48         <bean  id="collectionBean" class="com.study.spring.e_di.CollectionBean">
49             <!-- Injection of simple attributes -->
50             <property name="name" value="Gui Gu"></property>
51             <property name="age" value="12"></property>
52             <!-- injection list aggregate -->
53              <property name="hobbies">
54                  <list>
55                      <value>Having dinner</value>
56                      <value>Sleep</value>
57                      <value>Knock code</value>
58                  </list>
59              </property>
60              
61              <!-- injection set aggregate -->
62              <property name="numbers">
63                  <set>
64                      <value>10</value>
65                      <value>20</value>
66                      <value>30</value>
67                      <value>40</value>
68                      <value>50</value>
69                  </set>
70              </property>
71              <!-- injection map aggregate -->
72              <property name="map">
73                  <map>
74                      <entry key="birthday" value="2017-1-1"></entry>
75                      <entry key="address" value="Hangzhou West Lake"></entry>
76                      <entry key="sex" value="female"></entry>
77                  </map>
78              </property>
79              
80              <!-- injection Properties -->
81              <property name="properties">
82                  <props>
83                      <prop key="compamy">Hangzhou Gui Gu</prop>
84                      <prop key="pnum">200</prop>
85                  </props>
86              </property>
87         </bean>
88         
89     <!-- end  Bean Dependency Injection===================================================================================== -->    
90     <import resource="classpath:bean1.xml"/>        
91     <import resource="classpath:bean2.xml"/>        
92     <!-- Import here means if src There are others below. beans.xml We can call it this way. -->    
93         
94 </beans>

 

About the application Context. XML configuration file content must be understood, I wrote more basic and comprehensive.

I'll explain the use of namespace p here: _____________

P:<Attribute Name>= "xxx" Introduces Constant Values

P:<attribute name>-ref= "xxx" refers to other Bean objects

 

This article, I have written here, shortcomings, welcome you to give more advice, thank you!

Posted by unistake on Fri, 12 Apr 2019 09:27:31 -0700