Some knowledge points of Spring framework

Posted by thatshanekid on Tue, 14 Sep 2021 04:11:16 +0200

1. What is sprig

Spring is an open source framework., It was created by Rod Johson. It was created to understand the complexities that determine enterprise development

Spring uses basic JavaBeans to do things that previously could only be done by EJB s.

However, the use of Spring is not limited to server-side development. From the perspective of simplicity, testability and loose coupling, any java application can benefit from it.

Objective: to solve the complexity of enterprise application development.

Function: use basic JavaBeans instead of EJB s, and provide more enterprise application functions

Scope: any Java application

It is a container framework for loading JavaBeans (java objects). The middle tier framework can play a connecting role. For example, struts and hibernate are bonded together. In short, Spring is a lightweight control inversion (IOC) and aspect oriented (AOP) container framework.

 

IOC:Ioc - Inversion of Control, that is, "control reversal", is not a technology, but a design idea. In Java development, Ioc means that the object you designed is controlled by the container, rather than the traditional direct control inside your object.

AOP:AOP is the abbreviation of Aspect Oriented Programming, which means: Aspect oriented programming , pass precompile Mode and dynamic agent during operation is a technology to realize the unified maintenance of program functions. AOP is OOP The continuation of is a hot spot in software development and an important content in the Spring framework Functional programming A derived paradigm of. Using AOP, each part of business logic can be isolated, so as to make the connection between each part of business logic Coupling degree Reduce, improve the reusability of the program, and improve the efficiency of development.

Spring features: 1. Convenient decoupling and simplified development. 2   Through the IoC container provided by spring, we can integrate the dependencies between objects                                 The relationship is controlled by spring to avoid excessive program coupling caused by hard coding. With spring,                                   Users do not have to write code for the very low-level requirements such as single instance mode classes and property file parsing                                 To focus more on the application of the upper layer.  

                          2.AOP programming support      Through the AOP function provided by Spring, it is convenient for aspect oriented programming,                                   Many functions that are not easy to implement with traditional OOP can be easily handled through AOP.

                          3. Support for declarative transactions    In Spring, we can get rid of the tedious transaction management code                                 In order to improve the efficiency and quality of development, we can flexibly manage transactions in a declarative way.

                            4. Facilitate program testing      Almost all testing work can be carried out in a container independent programming way                                   In spring, testing is no longer an expensive operation, but an easy thing to do. For example: Spring pair                                         Junit4 support, you can easily test spring programs through annotations.

                            5. It is convenient to integrate various excellent frameworks      Spring does not exclude various excellent open source frameworks. On the contrary, spring can                                 To reduce the difficulty of using various frameworks, spring provides a variety of excellent frameworks (such as                                                       Struts,Hibernate, Hessian, Quartz), etc.

                             6. Reduce the difficulty of using java EE APL     Spring supports many difficult Java EE APIs (such as JDBC,                                     JavaMail, remote call, etc.) provides a thin encapsulation layer through the simple encapsulation of spring,                                   The difficulty of using these Java EE APIs is greatly reduced.

                              7. The source code is a classic learning example     Spring's source code is exquisitely designed, clearly structured, ingenious and unique                                     It embodies the master's flexible use of Java design patterns and his profound attainments in Java technology. Spring                                     The framework source code is undoubtedly a best practice example of Java technology. If you want to improve yourself quickly in a short time                                       Java technology level and application development level, learning and studying spring source code will make you get the idea                                       Can't get the effect.

Advantages of Spring: 1. Low intrusive design and extremely low code pollution. 2

                          2. Independent of various application servers, applications based on the Spring framework can truly realize write once and run                             Anywhere's commitment

                          3.Spring's DI mechanism reduces the complexity of business object replacement and improves the decoupling between components

                          4.Spring's AOP support allows centralized management of some common tasks, such as security, transactions, logs, etc,                             This provides better reuse

                          5.Spring's ORM and DAO provide good integration with the third-party persistence layer framework and simplify the underlying implementation                               Database access

                        6.Spring does not force applications to rely entirely on spring. Developers are free to choose parts or components of the spring framework                               whole

2. Coupling:

A measure of the degree of interconnection between different modules in a software architecture (coupling is also called inter block connection. It refers to a measure of the degree of close connection between modules in the software system structure. The closer the connection between modules, the stronger the coupling and the worse the independence of modules. The degree of coupling between modules depends on the complexity of the interface between modules, the way of calling and the information transmitted.)

Software engineering stipulates that the principle of writing code is "high cohesion and low coupling". Cohesion is the independence between code blocks, and coupling is the connection between code blocks.

3. The core of spring:

Control inversion (IOC):

  The implementation refers the relationship between components from the inside of the program to the external container (spring's xml) for management.

First, the external container (spring.xml) will dynamically register the objects (interfaces / classes) required by the business

Dependency injection (DI):

The dependency between components is determined by the container during the application system running period, that is, the container dynamically injects the target object instance of a dependency into each associated component in the application system

example:

For example, inject into xml

Class:

 

  Method of getting container registration by

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.openlab.opjo.Car;


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
     ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
     Car car=context.getBean("person", Car.class);
	   System.out.println(car);
//	
	System.out.println("============="); 
	}
}

Aspect oriented programming (AOP):

  Using a technology called "crosscutting", the interior of the unpacked object is dissected, and the public behaviors that affect multiple classes are encapsulated into a reusable module, which is named "Aspect", that is, Aspect. The so-called "Aspect" simply means that the logic or responsibilities that have nothing to do with the business but are jointly invoked by the business modules are encapsulated, which is convenient to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate the operability and maintainability in the future.

Using "crosscutting" technology, AOP divides the software system into two parts: core concerns and crosscutting concerns. The main process of business processing is the core concern, and the part that has little to do with it is the crosscutting concern. A characteristic of crosscutting concerns is that they often occur in multiple parts of the core concerns, and they are basically similar everywhere, such as authority authentication, logs and things. The role of AOP is to separate various concerns in the system and separate the core concerns from the crosscutting concerns.
 

4.IOC meaning

IOC, Inversion   of   Control)
In the traditional JAVA development mode, when an object is needed, we use new or directly or indirectly call the construction method through getInstance to create an object. In the Spring development mode, the Spring container uses the factory mode to create the required object for us. We don't need to create it ourselves. We can directly call the object provided by Spring, This is control reversal
 

5.DI:

Dependency injection. During the process of creating an object, Spring can set it according to the properties of the configuration object. This process is called dependency injection (DI)

Difference between IOC and DI:

IOC: control inversion refers to reversing the creation right of an object to the spring container.

DI: dependency injection refers to the injection of object dependent properties through configuration during object creation. The implementation of DI depends on IOC. There is control inversion before dependency injection

6. Attribute injection method

Construction method injection:

<bean id="car" class="com.openlab.opjo.Car">
      <constructor-arg name="baran" value="123we"></constructor-arg>
      <constructor-arg name="corp" value="red"></constructor-arg>
      <constructor-arg name="price" value="3425"></constructor-arg>
      <constructor-arg name="maxpeed" value="12"></constructor-arg>
      </bean>

set method injection:

      <bean id="car" class="com.openlab.opjo.Car">
      <property name="baran" value="123we"></property>
      <property name="corp" value="red"></property>
      <property name="price" value="3425"></property>
      <property name="maxpeed" value="12"></property>
      </bean>

p namespace injection

 <bean id="car" class="com.openlab.opjo.Car" p:baran="123we" p:corp="red"
       p:price="3425" p:maxpeed="12">
      </bean>

7. Injection set attribute:

Common collections in the Java.utils package

(1)List

(2)Set

(3)Map

(4)Properties

Spring provides corresponding tags for Collections:

< list > inject list elements

< set > inject set element

< Map > inject map elements

< props > inject the properties element (subclass of hashtable class, which is a special map, and both key and value are strings)
example:

Configure spring's core container

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="listperson" class="com.openlab.opjo.Listperson">
      <property name="Hobbies">
      <list>
      <value>having dinner</value>
       <value>sleep</value>
       <value>Beat beans</value>
       <value>drink water</value>
       </list>
      </property>
      </bean>
      
      
</beans>

Class:

package com.openlab.opjo;

import java.util.List;

public class Listperson {
	public List<String> Hobbies;

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

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

	@Override
	public String toString() {
		return "Listperson [Hobbies=" + Hobbies + "]";
	}
	

}

realization:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.openlab.opjo.Listperson;


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
     ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
     Listperson listperson=context.getBean("listperson", Listperson.class);
	   System.out.println(listperson);
//	
	System.out.println("============="); 
	}
}

Operation results:

  Note the map configuration (not value but entry):

 <map>

              <entry key="name" value="Zhang San"/>

              <entry key="age" value="22"/>

                <entry key="car" value-ref="car"></entry>

           </map>

The < props > injected properties elements are:

   <props>

              <prop key="name">Li Si</prop>

              <prop key="age">33</prop>

           </props>

Others are similar to List.

8. Scope of spring management Bean

The scope in Spring Bean is "scope" in the configuration file

In object-oriented programming, scope generally refers to the visible range between objects or variables.

In the Spring container, it refers to the request visibility range of the Bean object it creates relative to other Bean objects.

1.singleton

<bean id="listperson" class="com.openlab.opjo.Listperson" scope="singleton"></bean>  

When the bean scope is singleton, there will only be one shared bean instance in the Spring container. All requests for beans will only return the same instance of the bean as long as the id matches the bean definition. The singleton is stored in the singleton cache, which is the default scope of Spring (i.e. singleton by default).

2. prototype:

<bean id="listperson" class="com.openlab.opjo.Listperson" scope=" prototype "></bean>

When the Bean scope is prototype, Spring IoC will create a new scope (that is, a new object is obtained every time). Prototype should be used for stateful beans, and singleton should be used for stateless beans

3.    request:

<bean id="listperson" class="com.openlab.opjo.Listperson" scope=" request "></bean>

The Request scope is for each Http Request, and the Spring container will respond to the Request according to the related Bean

Definition to create a new Bean instance. Moreover, the Bean is valid only within the current request.

4.    session:

<bean id="listperson" class="com.openlab.opjo.Listperson" scope=" session "></bean>

For the http session, the Spring container will create a new instance of the Bean according to the definition of the Bean. Moreover, the Bean is valid only in the current http session.

5.    globalsession:

<bean id="listperson" class="com.openlab.opjo.Listperson" scope="globalsession"></bean>

Similar to the standard http session scope, but only meaningful in portlet based web applications. The portlet specification defines the concept of global session. It is shared by all the different portlets that make up an external application of a portlet. The bean s defined in the global session scope are limited to the life cycle of the global portlet session.

9. Life cycle of spring managed bean s:

  Case:

package com.openlab.opjo;


public class Listperson {
	public String name;

	
	public Listperson() {
		super();
		System.out.println("Nonparametric construction method");
	}

	public String getName() {
		
		return name;
	}

	public void setName(String name) {
		this.name = name;
		System.out.println("set Method execution");
	}

	public void init(){
		System.out.println("init Method execution");
	}
	public void destroy(){
		System.out.println("destroy Method execution");
	}

}

. xml file

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
      
      <bean id="listperson" class="com.openlab.opjo.Listperson" init-method="init" 
      destroy-method="destroy" p:name="Ruochen">
      </bean>
      

Test class:

import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.openlab.opjo.Listperson;


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
     Listperson listperson=context.getBean("listperson", Listperson.class);
	   System.out.println(listperson);
	   context.close();
//	
	System.out.println("============="); 
	}
}

result:

  Example 2:

package com.openlab.opjo;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;

public class Listperson1 implements BeanPostProcessor {
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("Before initialization");
		return bean;
	}


	@Nullable
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("After initialization");
		return bean;
	}
}
package com.openlab.opjo;


public class Listperson {
	public String name;

	
	public Listperson() {
		super();
		System.out.println("Nonparametric construction method");
	}

	public String getName() {
		
		return name;
	}

	public void setName(String name) {
		this.name = name;
		System.out.println("set Method execution");
	}

	public void init(){
		System.out.println("init Method execution");
	}
	public void destroy(){
		System.out.println("destroy Method execution");
	}

}
<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
      
      
      <bean id="listperson1" class="com.openlab.opjo.Listperson1"></bean>
      <bean id="listperson" class="com.openlab.opjo.Listperson" init-method="init" 
      destroy-method="destroy" p:name="Ruochen">
      </bean>
      
      
</beans>

Test class:

import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.openlab.opjo.Listperson;


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
     Listperson listperson=context.getBean("listperson", Listperson.class);
	   System.out.println(listperson);
	   context.close();
//	
	System.out.println("============="); 
	}
}

result

  10. Two methods of bean in spring

BeanFactory:
  BeanFactory is a relatively primitive and ancient Factory in spring. Because it is old, BeanFactory cannot support spring plug-ins, such as AOP and Web applications.

Get beans using BeanFactory

//XmlBeanFactory is a typical BeanFactory.
 BeanFactory factory = new XmlBeanFactory("XXX.xml");
 //Get a bean called mdzz. Instantiate at this time.
 factory.getBean("xxxx");

Important: when we use BeanFactory to obtain beans, we only instantiate the container, but the beans in the container are not instantiated. When we getBean, we will instantiate the bean object in real time.

ApplicationContext
  ApplicationContext is a subclass of BeanFactory. Because the old BeanFactory can not meet the needs of constantly updating spring, ApplicationContext basically replaces the work of BeanFactory. It works in a more framework oriented way, layers and inherits the context, and extends the functions on this basis:
<1> MessageSource, which provides international message access
<2> Resource access (such as URL s and files)
<3> Event delivery
<4> Automatic assembly of bean
<5> Context implementation of various application layers

Get bean using ApplicationContext

//When we instantiate XXX.xml, the beans configured in the file will be instantiated. (the bean scope is a singleton)
ApplicationContext appContext = new ClassPathXmlApplicationContext("XXX.xml");

  key point: when we use ApplicationContext to obtain beans, all configuration beans will be created when XXX.xml is loaded.

Three methods of obtaining ApplicationContext object references

/The first loading method is to load classpath The configuration file under.
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//The second loading method loads the files under the disk path.
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");
//The third loading method, XmlWebApplicationContext, loads from the web system.

//After getting the configuration file, you can get the desired object. For example:
HelloService helloService = (HelloService) applicationContext.getBean("userService");
//Among them, the parameters in getBean are the id and an id of the object under the configuration file.

Difference summary
<1> If you use ApplicationContext, if the configured bean is a singleton, it will be instantiated whether you have it or don't want to use it. The advantage is that it can be preloaded, and the disadvantage is a waste of memory.
<2> BeanFactory. When you instantiate an object using BeanFactory, the configured bean will not be instantiated immediately, but will not be instantiated until you use the bean (getBean). The advantage is to save memory, but the disadvantage is that the speed is relatively slow. It is mostly used for the development of mobile devices.
<3> Without special requirements, it should be completed using ApplicationContext. Because what BeanFactory can do, ApplicationContext can do, and provides more functions close to the current development.
 

Topics: Java Spring Spring Boot