Spring IOC Container Assembly Bean_XML-based Configuration

Keywords: Java Spring xml encoding Attribute

Develop required jar packages

Four ways to instantiate beans

1. parameterless constructors (most commonly used)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
    <!--1. parameterless constructor
    At instantiation time, the default constructor is called automatically, which is equivalent to MyBean mybean01 = new MyBean();
    -->
     <!--bean: Tell the Spring container which objects (beans) need to be handed over to the Spring container for management
    id/name: The unique identifier for the bean
    Class: The full class name of the bean (objects can be created using reflection at the bottom of the spring container)
    -->
    <bean id="mybean01" class="com.igeekhome.bean.MyBean"></bean>
</beans>
public class MyBean {
    public MyBean() {
        System.out.println("MyBean...Parameterless constructor called...");
    }
}

2. Static Factory Method

 <!--2.Static Factory Method
    MyFactory01.getBean()
    factory-method:Specify Static Factory Method
    -->
    <bean id="mybean02" class="com.igeekhome.bean.MyFactory01" factory-method="getBean"></bean>
public class MyFactory01 {
    //Static Factory Method
    public static MyBean getBean() {
        return new MyBean();
    }
}

3. Instance (non-static) factory method

<!--3.Non-Static Factory Method
    new MyFatory02().getBean
    -->
    <bean id="myfatory" class="com.igeekhome.bean.MyFactory02"></bean>
    <!--
    factory-bean:Reference to factory object
    factory-method: Factory Method Name
    -->
    <bean id="mybean03" factory-bean="myfatory" factory-method="getBean"></bean>
public class MyFactory02 {
    //Non-Static Factory Method
    public MyBean02 getBean() {
        return new MyBean02();
    }
}

4.FactoryBean (low-level source used more)

<!--4.FactoryBean
    MyFactoryBean:spring first checks if the class implements the FactoryBean interface, and if it does not, creates the object directly and adds it to the container
    If you implement the FactoryBean interface, call the getObject method and add the method return value object to the container
    -->
    <bean id="mybean04" class="com.igeekhome.bean.MyFactoryBean"></bean>
//Create a factory object to implement an interface for FactoryBean<Bean4>
public class MyFactoryBean implements FactoryBean<MyBean03> {//Generics: What type of object do you want to return and what is a generic
    @Override
    public MyBean getObject() throws Exception {
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }
}

Scope of Bean

When is a bean object created by spring valid

Usually used in project development: singleton singleton, prototype multiple

  • Singleton: In a spring container, there is only one instance of the object (default value)
  • Prototype: In a spring container, there are multiple instances, and each getBean returns a new instance
<!-- bean Scope of action
       scope:Configure scope, default value is singleton Singleton
     -->
<!-- Singleton -->
<!-- <bean id="singletonBean" class="com.igeek.scope.SingletonBean"></bean> Equivalent to -->
    <bean id="singletonBean" class="com.igeek.scope.SingletonBean" 
    scope="singleton"></bean>
    
    <!-- Multiple Cases -->
    <bean id="prototypeBean" class="com.igeek.scope.PrototypeBean" 
scope="prototype"></bean>

Bean initialization and destruction methods

Specify the Initialized Call Method through the init-method property
Specify the method before destroying the object through the destroy-method property

 <!--
    init-method: Specifies the initialization method
    destroy-method: Specifies the destroy trigger method
    -->
    <bean id="lifecycle" class="com.igeekhome.bean.LifeCycleBean" scope="singleton" init-method="initMethod" destroy-method="destroyMethod"></bean>
public class LifeCycleBean {

    public LifeCycleBean() {
        System.out.println("Constructor...");
    }

    public void initMethod() {
        //...perform initialization
        System.out.println("init...method...");
    }

    public void destroyMethod() {
        System.out.println("destroy...method...");
    }
}
The execution of the destruction method must satisfy two conditions
  • Only singleton bean s can be destroyed manually
  • Manual destroy method is executed only when the container must be closed manually (the close method is called)

Test initialization and destruction methods:

public class Test03 {
    private ApplicationContext ac = null;
    @Before
    public void before() {
        ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    @Test
    public void method01() {
        LifeCycleBean lifeCycleBean = ac.getBean("lifecycle", LifeCycleBean.class);
        //Close ioc container
        ((ClassPathXmlApplicationContext) ac).close();
    }
}

Post-processing Bean (BeanPostProcessor interface)

Postprocessor Beans, also known as Beans, enhance Bean objects before and after Bean initialization.It can enhance either a specified Bean or all Beans. Many of the underlying functions (such as AOP) are implemented based on it, and Spring can directly identify calls in containers

////bean's Post Processor: Enhance beans by implementing enhancements to the initialization of all, or one, beans
public class MyBeanPostProcessor implements BeanPostProcessor{
    /*bean Before instantiation
       bean: object
       beanName:  bean id/name of
     */
    //Initialized (before)
    public Object postProcessBeforeInitialization(Object bean, String beanName)throws BeansException {
        //System.out.println(beanName+ "Enhanced before initialization");
       //How to enhance only one bean
       if(beanName.equals("lifeCycleBean")){
           System.out.println(beanName+"Enhancement started before initialization");
       }
       return bean;//Release
    }
    
    //Initialize (after) call
    public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {
        //System.out.println(beanName+ "Enhanced since initialization");
       if(beanName.equals("lifeCycleBean")){
           System.out.println(beanName+"Enhancement started after initialization");
       }
       return bean;
    }
}

Dependent Injection (DI) of Bean Properties

1.setter method property injection

public class Person {
    private int no;
    private String name;
    private boolean status;
    private Car car;

    public Person() {
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Person{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", status=" + status +
                ", car=" + car +
                '}';
    }

    public Person(int no, String name, boolean status, Car car) {
        this.no = no;
        this.name = name;
        this.status = status;
        this.car = car;
    }
}

public class Car {
    private String no;
    private String brand;
    private double price;

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Car{" +
                "no='" + no + '\'' +
                ", brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }

    public Car() {
    }

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

    public Car(String no, String brand, double price) {
        this.no = no;
        this.brand = brand;
        this.price = price;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.igeekhome.di.Person">
        <!--setter Injection: Prerequisite Satisfaction JavaBean Specification (provided) setter Method)-->
        <!--property:setter injection
            name:Property Name (Specifically set Method name in lowercase)xyz -> Called by default setXyz()
            value: Simple value
            ref:Injected bean Of id Put one of the containers bean Inject into another bean in
        -->
        <property name="no" value="123"></property>
        <property name="name" value="Zhang San"></property>
        <property name="status" value="true"></property>
        <property name="car" ref="car"></property>
        <!--equivalence-->
        <!--<property name="car">
            <ref bean="car"></ref>
        </property>-->
    </bean>

    <bean id="car" class="com.igeekhome.di.Car">
        <property name="brand" value="BMW"></property>
        <property name="price" value="66666"></property>
    </bean>

</beans>

2. Constructor parameter injection

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="car" class="com.igeekhome.di.Car">
        <!--Use constructor Construction Injection
        value:
        ref:  Ditto
        type: Constructor type needs to write full class name if it is a reference (Each field is inconsistent)
        index: The index position of the construction parameter starts at 0
        name: Name of construction parameter
        -->
        <constructor-arg name="brand" value="BMW"></constructor-arg>
        <constructor-arg name="price" value="66666"></constructor-arg>
        <constructor-arg name="no" value="001"></constructor-arg>
    </bean>

    <bean id="person" class="com.igeekhome.di.Person">
        <constructor-arg index="0" value="111"></constructor-arg>
        <constructor-arg index="1" value="Li Si"></constructor-arg>
        <constructor-arg index="2" value="false"></constructor-arg>
        <constructor-arg index="3" ref="car"></constructor-arg>
    </bean>

</beans>

3.p Namespace

To simplify the configuration of XML files, Spring 2.5 introduced a new p namespace.Simply put, its purpose is to simplify setter method property dependency injection configuration, it is not a real namespace

How to use it:

P:<property name>="xxx" introduces constant value
 P:<property name>-ref="xxx" refers to other Bean objects
<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p Namespace injection:
    //Prerequisite: setter-based injection
    p:attribute = ""
    p:attribute-ref = ""
    -->
    <bean id="person" class="com.igeekhome.di.Person" p:name="Zhang San" p:no="002" p:status="false" p:car-ref="car">
    </bean>
    <bean id="car" class="com.igeekhome.di.Car" p:brand="qq" p:price="66666">
    </bean>
</beans>

4.spEL expression

SpEL (Spring Expression Language) is an expression language, which is a new feature of Spring 3.x.Its purpose is to support the operation and query of objects at runtime. Its syntax is similar to the uniform EL language, but SpEL provides additional functionality and is more powerful

Syntax: #{...}, referencing another Bean, property, method
SpEL expressions are useful, and Bean operations are usually related to:

#{beanId} Reference Bean (concrete object)
#{beanId.Properties}Reference Bean's Properties
 #{beanId.method (parameter)} Call Bean's method
<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="person" class="com.igeekhome.di.Person" p:name="Zhang San" p:no="002" p:status="false" p:car="#{car2}">
    </bean>
    <bean id="car" class="com.igeekhome.di.Car" p:brand="qq" p:price="66666">
    </bean>
    <bean id="car2" class="com.igeekhome.di.Car" p:no="#{car.no}" p:brand="#{car.brand.toUpperCase()}" p:price="#{car.price}">
    </bean>
</beans>

Posted by timgolding on Thu, 05 Dec 2019 19:32:25 -0800