On October 28, 2021, Spring learns Bean construction, setting, injection, single instance and multiple instances, lazy loading, initialization and destruction

Keywords: Java Spring intellij-idea

Non intrusive: many classes have been written in the system, and now a new technical framework can be used. While using the new framework, the original class does not need to be changed (there is no need to inherit and implement the interface in the new framework). Framework: Spring, Hibernate, Mybatis

Intrusive: many classes have been written in the system, and now a new technical framework is introduced, which can be used. While using the new framework, the original class needs to be changed. Such as Struts and Servlet

IoC and DI:
IoC: (inversion of Control) control inversion, which mainly solves the problem of object creation
DI: (dependency injection) dependency injection, which mainly solves the problem of object relationship (object dependency)

AOP: (aspect - oriented programming)
OOP: (Objiect -Oriented Programming)
Aspect: simply understood as a class (with interception function), it does not affect the normal business logic processing, but does some additional operations before or after the normal logic processing.
Purpose: used to set account permissions and intercept

Spring Download
Download: Spring official website( https://spring.io/ )-github (Maven, traditional)
Open source China: oschina
Version: 5.0.2.RELEASE
Spring2 - Spring 3 (supports @ Annotation)
Some new features of Spring 4.0:
A) Full support for Java 8
B)Web support has been upgraded to support Servlet 3.0 and later specifications
C) Support Groovy DSL for Bean configuration
D) A new spring websock module has been added

Starting with Servlet 3.0, annotation methods are supported, such as @ WebServlet
Servlet versions below 3.0 do not support annotations and must be written in web.xml.

<?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:util="http://www.springframework.org/schema/util"
       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/util
        http://www.springframework.org/schema/util/spring-util-5.0.xsd">
       
    <bean id="per" class="org.jabari.spring.core.beans.Teacher"/>
</beans>

If an error is reported after writing

It indicates that the dependency library is not imported into the environment. We need to add new code in prom.xml


<bean id = "per" class="org.jabari.spring.core.beans.Teacher"/>

Beans can help us manage objects and create files

Create the directory org.jabari.spring.core.beans that the bean knows

Function of constructor: for detailed code explanation, please see another blog on that day
This code means to build an object

ApplicationContext ctx = new
                ClassPathXmlApplicationContext("applicationContext.xml");

get a bean from the context. The bean name is per. We have defined it in applicationContext.xml,

    <bean id="per" class="org.jabari.spring.core.beans.Teacher"/>

After you get the Teacher, Person.class means that Teacher is a subclass of Person

  Person pSpring = ctx.getBean("per",Person.class);
        pSpring.biz();

Note that during bean construction injection

<bean id="per" class="org.jabari.spring.core.beans.Teacher"/>

The parameterless constructor will be called, so we need to pay attention to whether the parameterless constructor exists when the parameterless constructor is created in the new class

Thinking: so how can we call a parameterized constructor without writing a parameterless constructor?
answer:
Method 1: use to inject Bean. The value in constructor Arg here is the value of the constructor parameter you build

<bean id="teacher" class="org.jabari.spring.core.beans.Teacher">
		<constructor-arg index="0" value="430421111111111"/>
		<constructor-arg index="1" value="26"/>
		<constructor-arg index="2" value="Zhang San"/>
	</bean>

index="0, 1, 2, 3" the values in index represent the parameters of the constructor with parameters

Method 2: use c: namespace to simplify configuration
Development process:
Step 1: add the following in the beans header of the xml file:
xmlns:c="http://www.springframework.org/schema/c"
Step 2: use c in xml to configure, as follows:

<bean id="teacher2" class="org.jabari.spring.core.beans.Teacher" 
		c:_2="LiSi" c:_0="12345" c:_1="28">

Principle of underlying reflection mechanism:

String classStr = "org.jabari.spring.core.beans.Person";

Class clz1 = Class.forName(classStr);
Constructor cons = clz1.getConstructor(new Class[]{
		String.class,int.class,String.class
});

Person pe = (Person)cons.newInstance(new Object[]{"1111132",32,"Parametric constructor"});
System.out.println("name="+pe.getName());
System.out.println("age="+pe.getAge());
System.out.println("identity="+pe.getIdentity());

xmlns:p="http://www.springframework.org/schema/p"

Step 2:

Why do you need to use ref = "addr1" in addr in the penultimate row?
Because the data types are inconsistent. When the data type is int or number, you can use value, but when the data type is complex, you need to use ref for reference

Scope = "singleton", the default value, that is, the default value is single instance [service/dao / tool class] scope = "prototype", multiple instances; Action object



Output results

As you can see, although the output addr1 is written three times in our code, it is only executed once, indicating that the default is a singleton.

If we want to set multiple instances, we can

 <bean id="addr1" class="org.jabari.spring.core.beans.Address" scope="prototype">
        <constructor-arg index="0" value="Hunan Province"/>
        <constructor-arg index="1" value="Changsha City"/>
        <constructor-arg index="2" value="Open service area"/>
</bean>

The result of running again at this time:

This is called three times, although our code

Address addr1 = ctx.getBean("addr1", Address.class);

Only twice, but

 AbstractApplicationContext ctx = new
                ClassPathXmlApplicationContext("applicationContext.xml");

It will also be executed once by default when loading the configuration, so there are three times

Delay creation

<beans default-lazy-init="false"  />

Lazy init = "false" the default value is false. Creation is not delayed, that is, objects are created at startup

Lazy init = "true" delay initialization. Objects are created only when they are used (only valid for single instances). Lazy loading and delay loading. When they are used, they are loaded again, not when they are started.

Initialize / destroy after object creation

init-method="init"
[the init method of the corresponding object is executed after the object is created]

destroy-method="destroy"
[executed when calling the destroy method of the container object, (container implementation class)]


Destruction:
If the destroy method is executed successfully, the - Address object will be output
You need to change the method of loading the context bean
Change ApplicationContext to AbstractApplicationContext
Because there is a destruction container in it, it needs to be changed

public class TestBean03 {

    public static void main(String[] args) {
        AbstractApplicationContext ctx = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("------------1------------");
        Address addr1 = ctx.getBean("addr1", Address.class);
        System.out.println("------------2------------");
        Address addr2 = ctx.getBean("addr1", Address.class);
        System.out.println("------------3------------");

        // Destroy container object
   //     ctx.close();
        ctx.registerShutdownHook();

    }


At the same time, if destruction is required, multiple instances cannot be configured in the bean configuration file, and the default single instance should be used.

Here are several examples of similar functions with automatic startup, which cannot be completely closed. When you need to use it, you can't close it even with close().

Four ways of BEAN initialization and destruction
Reference website: https://www.freesion.com/article/58011376370/
Method 1: specify the bean initialization method and bean destruction method
Method 2: initialize and destroy beans through InitializingBean and DisposableBean interfaces
Method 3: annotation @ PostConstruct and @ ProDestory provided by JSR250 specification
Method 4: the bean post processor of Spring's BeanPostProcessor will intercept all bean creation processes

Posted by codygoodman on Thu, 28 Oct 2021 13:00:19 -0700