spring framework Basics

Spring framework

1, Spring framework overview
1. Spring is a service layer framework that can integrate many other frameworks to work.
2. Main technologies of Spring:
(1)IOC(DI)
Inversion of control (dependency injection): low coupling - code separation and easy code reuse
(2)AOP
Aspect oriented programming: high cohesion - clear structure, easy to develop and maintain
2, Control reversal (low coupling)
The mechanism by which the Spring framework manages object creation and lifecycle is called inversion of control

1. Create a Spring project

2. Import jar package

3. Create an xml configuration file for Spring

4. Configuring the Person class

idIdentifies the class name of the configured bean
classIdentifies the full path to configure this class
<bean id="person" class="cn.tedu.domain.Person">

5. Spring implements the underlying principle of IOC

@Test
public void test02(){
    //1. Initialize the container: discover the configuration file and start parsing the Spring configuration file
    ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
    //2. Create an object through the Spring container and get the person class
    Person person =(Person)context.getBean("person");
    person.eat();
    person.sleep();
    //3. Close the Spring container
    //ClassPathXmlApplicationContext has close();ApplicationContext does not have a close ()
    ((ClassPathXmlApplicationContext)context).close();
}

Corollary 1: bean s with the same id can be obtained multiple times, and the obtained values are the same
Corollary 2: multiple bean s with the same id cannot be configured
Inference 3: multiple bean s with the same class but different IDS can be configured
6. How to get objects:
(1) Get object by id (common)

Person p = (Person)context.getBean("person");//cn.tedu.domain.Person@65e
Find uniqueReturn object
can't findNoSuchBeanDefinitionException
Multiple foundImpossible. id is the unique id

(2) Get objects through class

Person p1 = context.getBean(Person.class);
Find uniqueReturn object
can't findFind the descendant bean of this type, and return the descendant object if found
Can't find itNoSuchBeanDefinitionException
Multiple foundIt is possible to find more than one and throw an exception NoUniqueBeanDefinitionException

(3) Specify id alias
name: specify the id of the corresponding bean, and alias specifies the new id

<alias name="person" alias="person2"></alias>

7. Create Spring objects
The essence of Spring creating objects: creating objects through the class's parameterless constructor.
(1) Nonparametric structure

<bean id="person" class="cn.tedu.domain.Person"></bean>

Implementation principle: when the Spring container is initialized, the bytecode file is reflected through the class attribute configured on, and the instance object is created through newInstance(). The class of this method can only have parameterless construction methods, otherwise reflection cannot be used.
(2) Parametric structure
Implementation principle: by configuring bean parameters, you can control the Spring container to create objects through the specified constructor, rather than through the default parameterless constructor

indexAll three do not need to be set. There is no ambiguity. You can have the first parameter of parameter construction, starting from 0
nameParameter name
typeParameter type
valueThe specific meaning given by one of two choices (basic data type or String type)
refAssigned value (reference data type)

configuration file

<bean id="person2" class="cn.tedu.domain.Person2">
    <constructor-arg index="0" name="name" type="java.lang.String" value="lili"></constructor-arg>
    <constructor-arg index="1" name="age" type="int" value="10"></constructor-arg>
</bean>

Person2

public Person2(String name,int age){
    System.out.println("person2,name:"+name+",age:"+age);
}

Test

//Creating objects with parametric constructs
@Test
public void test05(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Person2 p = (Person2)context.getBean("person2");
    System.out.println(p);
    ((ClassPathXmlApplicationContext)context).close();
}


(3) Static factory
Implementation principle: because you want to use the specified static method to instantiate the object, you have to privatize the parameterless constructor in the static factory class.
Create an object through a factory: if the created object needs several settings before it can be used, spring also supports creating bean s through a factory.
Factory design pattern: encapsulate the details of creating objects through a factory class, and then create objects through factories to simplify the process of creating objects.
NetConn.java

public class NetConn {//Realize the function of querying data after connecting to the network
    public void load(){   System.out.println("Load profile...");  }
    public void ping(){ System.out.println("Test network..."); }
    public void conn(){System.out.println("Connect network...");}
    public void login(){System.out.println("Sign in...");}
    public void sendData(){System.out.println("send data..."); }
}
NetConnStaticFactory.java
public class NetConnStaticFactory {//Create a factory class to encapsulate network connection and login operations
private NetConnStaticFactory(){}//Privatized nonparametric construction method
    public static NetConn getNetConn(){//Create an object of NetConn class
        NetConn nc = new NetConn();//These methods are called by nc to complete the encapsulation of methods
        nc.load();
        nc.ping();
        nc.login();
        return nc;
    }
}

applicationContext.xml

<!-- Purpose of configuring static factory method:Creates an object through the specified static factory method
 The operation has already occurred NetConn conn=NetConnStaticFactory.getNetConn();-->
<bean id="nc" class="cn.tedu.domain.NetConnStaticFactory" factory-method="getNetConn"></bean>

TestDemo.java

public void test01(){
    //Premise: sendData() is called directly using the object of NetConn class, and no connection check operation is required
    //Load profile
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get bean: get the instance object conn created by the Spring container
    //The data type of nc must be NetConn, and then the sendData() method can be called directly using this object
    NetConn nc =(NetConn) context.getBean("nc");
    nc.sendData();
    //Close the Spring container
    ((ClassPathXmlApplicationContext)context).close();
}

(4) Example factory
Implementation principle: the method in the instance factory is not static, so you cannot directly call the custom factory method to instantiate the object. (because. xml is loaded before. java files), configure the bean of the factory object first, create a factory object at the bottom, and then configure the custom factory method to instantiate the object.
NetConnInstanceFactory.java

public class NetConnInstanceFactory {
    private NetConnInstanceFactory(){}//Privatized nonparametric construction method
    public NetConn getNetConn(){//Create a non static factory method
        NetConn nc = new NetConn();
        nc.load();
        nc.ping();
        nc.login();
        return nc;
    }
}

applicationConext.xml

 <bean id="NetConnInstanceFactory" class="cn.tedu.domain.NetConnInstanceFactory"></bean>
<!-- Equivalent to giving netConn An instance object is also prepared-->
    <bean id="netConn" factory-bean="NetConnInstanceFactory" factory-method="getNetConn"></bean>

TestDemo.java

public void test02(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //Get the bean tag with id of NetConn (equivalent to getting the instantiated NetConn object)
    NetConn netConn = (NetConn) context.getBean("netConn");
    netConn.sendData();
    ((ClassPathXmlApplicationContext)context).close();
}

(5) Spring Factory
Implementation principle: let ordinary factories implement FactoryBean interface; Create the production object in the factory class; Then configure bean ID and bean class in the. xml file to instantiate the object.
NetSpringFactory.java

public class NetConnSpringFactory implements FactoryBean<NetConn> {
      @Override  //Create production target
    public NetConn getObject() throws Exception {
        NetConn nc = new NetConn();
        nc.load();
        nc.ping();
        nc.conn();
        nc.login();
        return nc;
    }
       @Override //Gets the type of the target object
    public Class<?> getObjectType() { return NetConn.class; }
        @Override//Controls whether the production target object is a singleton
    public boolean isSingleton() {return false;}
}

applicationContext.xml

<bean id="nc" class="cn.tedu.domain.NetConnSpringFactory"></bean>

TestDemo.java

@Test
public void test03(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    NetConn nc = (NetConn)context.getBean("nc");
    nc.sendData();
    ((ClassPathXmlApplicationContext)context).close();
}

(6) Single case, multiple cases

(7) Lazy loading mechanism
Configuring lazy init = true on the singleton tag will set to lazy loading mode. In this mode, bean objects will not be created when the container is initialized, but when the object is used for the first time, thus reducing the consumption of time and space for container startup.
Lazy loading is only effective for single instance bean tags (lazy loading itself is multiple instances); Lazy loading only delays the creation of the object, and the object is still a singleton.
overall situation

local

<bean id="person" class="cn.tedu.domain.Person" lazy-init="false"></bean>

If it is set at the same time, it will take effect locally
(8) Spring implements custom initialization and destruction methods for configuration

<bean id="nc" class="cn.tedu.domain.DBUtils" init-method="init" destroy-method="destroy"></bean>

NetConn.java

public class NetConn { //Realize the function of querying data after connecting to the network
    public void init(){System.out.println("Connect to database...");}
    public void sendData(){
        System.out.println("send data...");
    }
    public void destroy(){System.out.println("Disconnect database..");}
}

TestDemo.java

@Test
public void test04(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    NetConn nc = (NetConn)context.getBean("nc");
    nc.sendData();
    ((ClassPathXmlApplicationContext)context).close();
}

Posted by thompsonsco on Sun, 24 Oct 2021 03:30:07 -0700