spring for beginners

Spin official website: Spring | Home

Spring family bucket     Architecture scheme level
spring struts Hibernate
spring springmvc mybatis
springboot     dubbox (protest with Spring chamber from 16 to 19)
SpringCloud

Technical level
Security technology: Shiro         springSecurity
Database level: hibernate/mybatis     SpringDataJpa
Message Oriented Middleware: activityMQ, RabbitMQ, kaffka     spring..MQ
....

1, Overview of spring framework

1.1 what is spring

Spring is an open source framework created by Rod Johnson. It is created to solve the complexity of enterprise application development.

    Spring uses basic JavaBean s 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 Spring.
      Objective: to solve the complexity of enterprise application development
      Function: use basic JavaBean s instead of EJB s, and provide more enterprise application functions
     Scope: any Java application
      Simply put, Spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

    It is a container framework used to hold java beans (java objects), and the middle layer framework (all-purpose glue) can play a connecting role, such as bonding Struts and hibernate together. Simply put, Spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

① , middle layer frame, universal glue
       struts2, spring, hibernate
② . container frame
      JavaBean      Classes in the project
      IOC and AOP

Integration between frameworks is required:

 

  spring contains core modules:

  2.2,   What is inversion of control (or dependency injection)  

In vernacular terms, IOC = inversion of control is controlled by the container (dependency) relationship between programs, rather than directly controlled by program code in traditional implementation. This is the concept of the so-called "control reversal": (dependency) the control right is transferred from the application code to the external container. The transfer of control right is the so-called reversal.
    IoC has another name: "Di = dependency injection"  , That is, the container dynamically injects a dependency into the component

IOC/DI
      spring handles the instantiation / assignment of objects previously done by programmers

2.3,   How to define and configure a JavaBean in spring (create a JavaBean using parameterless construction method + set method)

① id: find the id of the Bean in the container (unique and cannot start with /)
    ② Class: the full class name of the bean
    ③ Name: find the name of the Bean in the container (unique, allowed to start with /, allowed multiple values, separated by commas or spaces)
    ④ scope:(singleton|prototype) the default is singleton
      ④ . 1 singleton (singleton mode): in each Spring IoC container, a bean definition corresponds to an object instance
      ④ . 2 prototype mode: a bean definition corresponds to multiple object instances
    ④ Abstract: define a bean as an abstract bean (Abstract beans cannot be instantiated). Abstract classes must be defined as abstract beans, and non abstract classes can also be defined as abstract beans
    ⑤ Parent: specify a parent bean (inheritance relationship is required)
    ⑥ Init method: Specifies the initialization method of the bean
    ⑦ Constructor Arg: create a javaBean using a parameterized constructor
    Note 1: for the Action of struts 2, please use the multi instance mode

2.4. Simple attribute configuration:

8 + 1 + 3: 8 basic data + String+3 sql

java.util.Date, java.sql.Date, java.sql.Time,java.sql.Timestamp
    You can assign values through the < value > tag

2.5. Configuration of complex attributes

  ① JavaBean: ref bean=""   ② List or array   ③ Map   ④ Properties

2.6,   For the project, there are two ways to write the configuration file path

   ApplicationContext
   String path = "applicationContext.xml";
   String path = "classpath:applicationContext-*.xml";//src
    String[] path = new String[] { "applicationContext-a.xml", "applicationContext-b.xml" };// Sub module development

2.7. Integration of spring and web projects

    How WEB projects read spring context
    Implementation of ServletContextListener through listener
   contextConfigLocation:classpath:applicationContext-*.xml

2.8, log4j2

2.9. spring.pom,spring-context, spring-orm,spring-web,spring-aspects
    Note: when creating spring XML files, you need to add beans/aop/tx/context tag support

2, IOC

2.1. What is IOC

Case: realize the upload function of spring's IoC. The difference between common writing and spring writing

Related classes used:

package com.zxy.ioc.biz;
/**
 * Interface
 * @author zjjt
 *
 */
public interface UserBiz {
	
public void upload();
	

}

(1) Common writing

① , first version (original version)

package com.zxy.ioc.biz.impl;
import com.zxy.ioc.biz.UserBiz;
/**
 * Requirements: do an upload function
 * Function: upload function
 * Propose rectification:
 * 1,Limit upload file size 2. Limit upload file category
 * Summary:
 * 1,The updated version needs to change the original code
 * 2,There is a huge risk associated with the modules that call this method
 *
 *action1   Restrictions are needed
 *action2   No restrictions are required
 */
public class UserBizImpl1 implements UserBiz{
	
	public void upload() {
//      Code for rectification, error reporting and withdrawal
//		System.out.println("make conditional judgment and limit, the file is too large to upload");
		System.out.println("Follow the rules and develop the functions");
		
	}
}

Second version (updated version)

package com.zxy.ioc.biz.impl;
import com.zxy.ioc.biz.UserBiz;
public class UserBizImpl2 implements UserBiz{
	public void upload() {
		System.out.println("Make conditional judgment and limit. The file is too large to upload");
		System.out.println("Follow the rules and develop the functions");
		
	}
}

② Suppose there are two modules to use (one is this module and one is associated module)

UserAction :

package com.zxy.ioc.web;
/**
 *This uses the first version
 */
import com.zxy.ioc.biz.UserBiz;
import com.zxy.ioc.biz.impl.UserBizImpl1;
public class UserAction {
	private UserBiz userBiz=new UserBizImpl1();
	public void upload() {
		userBiz.upload();
	}
 
	public static void main(String[] args) {
		UserAction userAction=new UserAction();
		userAction.upload();
		
	}	
}

result:  

 PersonAction :  

package com.zxy.ioc.web;
/**
 *This uses the second version
 */
import com.zxy.ioc.biz.UserBiz;
import com.zxy.ioc.biz.impl.UserBizImpl1;
import com.zxy.ioc.biz.impl.UserBizImpl2;
public class PersonAction {
	private UserBiz userBiz=new UserBizImpl2();
	public void upload() {
		userBiz.upload();
	}
	
	public static void main(String[] args) {
		PersonAction personAction=new PersonAction();
		personAction.upload();	
	}
}

  result:

  If there are 100 modules that need to be corrected, the original code needs to be changed 100 times (cumbersome);

At the same time, the relevant modules calling this method are accompanied by huge risks;

(2)spring writing

① . import jar dependency (pom.xml file)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zxy</groupId>
  <artifactId>Spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>maven_4 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<spring.version>5.0.1.RELEASE</spring.version>
		<javax.servlet.version>4.0.0</javax.servlet.version>
		<junit.version>4.12</junit.version>
	</properties>
  <dependencies>
    <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- 2,Import spring rely on -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- 5.1,junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- 5.2,servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${javax.servlet.version}</version>
			<scope>provided</scope>
		</dependency>
  </dependencies>
  <build>
    <finalName>Spring</finalName>
    <plugins>
    <plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
    </plugins>
  </build>
</project>

② , import xsd constraint (spring-context.xml)

If you need to update, you can directly modify the configuration without modifying the original code;

If there is an update error, change userBiz2 to userBiz1 directly before updating;

<bean name="personAction" class="com.zxy.ioc.web.PersonAction">
     <property name="userBiz" ref="userBiz2"></property>
</bean>
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<!--This file configures all the information contained in the entire project javabean  The purpose is spring unified management -->
<bean name="userBiz1" class="com.zxy.ioc.biz.impl.UserBizImpl"></bean>
<bean name="userBiz2" class="com.zxy.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.zxy.ioc.web.PersonAction">
<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.zxy.ioc.web.UserAction"></bean>


</beans>

③ , test and results

package com.zxy.ioc.web;
/**
 *This uses the second version
 */
import com.zxy.ioc.biz.UserBiz;
import com.zxy.ioc.biz.impl.UserBizImpl;
import com.zxy.ioc.biz.impl.UserBizImpl2;
public class PersonAction {
//	Original writing
//	private UserBiz userBiz=new UserBizImpl2();
	
	//spring writing
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
 
	
	public void upload() {
		userBiz.upload();
	}
	
}

main test  

package com.zxy.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.ioc.web.PersonAction;
import com.zxy.ioc.web.ParamAction;
/**
 *Test class
 */
public class IocTest {
	public static void main(String[] args) {
		//Step 1: model the spring-context.xml file
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		PersonAction personAction = (PersonAction)applicationContext.getBean("personAction");
		personAction.upload();		
	}
}

Results obtained:

   2. spring pass parameters

Assign initialization value to javabean   Transmission parameter
(1) . set parameters
(2) Structural parameters
(3) . automatic assembly (basically not used)

① . set parameters

ParamAction :

package com.zxy.ioc.web;
import java.util.List;
public class ParamAction {
	private int age;
	private String name;
	private List<String> hobby;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<String> getHobby() {
		return hobby;
	}
	public void setHobby(List<String> hobby) {
		this.hobby = hobby;
	}
	
	public void execute() {
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
 
	}
}

  Configuration (spring-context.xml)

<bean name="paramAction" class="com.zxy.ioc.web.ParamAction">
     <property name="name" value="Senior people"></property>
     <property name="age" value="18"></property>
     <property name="hobby">
           <list>
                <value>Dribble</value>
                <value>Step on Xiaoliu</value>
           </list>
     </property>
</bean>

Test:

package com.zxy.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.ioc.web.PersonAction;
import com.zxy.ioc.web.ParamAction;
/**
 *Test class
 */
public class IocTest {
	public static void main(String[] args) {
		//Step 1: model the spring-context.xml file
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction paramAction = (ParamAction)applicationContext.getBean("paramAction");
		paramAction.execute();
		
	}
}

Operation results:

② Structural parameters

ParamAction :

package com.zxy.ioc.web;
import java.util.List;
public class ParamAction {
	private int age;
	private String name;
	private List<String> hobby;
	public ParamAction() {
		// TODO Auto-generated constructor stub
	}
	
	public void execute() {
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
 
	}
 
	public ParamAction(int age, String name, List<String> hobby) {
		super();
		this.age = age;
		this.name = name;
		this.hobby = hobby;
	}
}

Configuration (spring-context.xml)

<bean name="paramAction" class="com.zxy.ioc.web.ParamAction">
     <constructor-arg name="name" value="Senior 2"></constructor-arg>
     <constructor-arg name="age" value="18"></constructor-arg>
     <constructor-arg name="hobby">
          <list>
               <value>Didi 1</value>
               <value>Step on Xiaoliu 1</value>
          </list>
     </constructor-arg>
</bean>

Test:

package com.zxy.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zxy.ioc.web.PersonAction;
import com.zxy.ioc.web.ParamAction;
/**
 *Test class
 */
public class IocTest {
	public static void main(String[] args) {
		//Step 1: model the spring-context.xml file
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction paramAction = (ParamAction)applicationContext.getBean("paramAction");
		paramAction.execute();
		
	}
}

result:

  3. spring and Tomcat integration  

If hundreds of classes are configured in spring-context.xml, the time process of test modeling is very long;

Each time a java bean is modeled, the longer it takes, the worse its performance;

This line of code will be executed for a long time, so this line of code can only be executed once in the project. Put it into the listener

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");

1. Listener: SpringLoaderListener implementation   ServletContextListener interface

package com.zxy.ioc.listenner;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringLoaderListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//This method has and will only be executed once. If Tomcat starts to execute once, it will not be executed again
		System.out.println("Listener method execution----");
		//Put the modeling process into the listener for execution
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		//Save it in Tomcat context;
		sce.getServletContext().setAttribute("SpringContext", applicationContext);
		
	}
}

2. Configuring listeners in web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
  <display-name>Archetype Created Web Application</display-name>
  
  <listener>
        <listener-class>com.zxy.ioc.listenner.SpringLoaderListener</listener-class>
  </listener>
  
</web-app>

3. Test and results

① , test UserServlet  

package com.zxy.ioc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@WebServlet("/user")
public class UserServlet extends HttpServlet{

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
ApplicationContext springContext= (ApplicationContext) req.getServletContext().getAttribute("SpringContext");
ParamAction paramAction = (ParamAction) springContext.getBean("paramAction");
paramAction.execute();
	}

}

② . result: the listener will execute only once, and the result can be executed multiple times

  It's over!

Keywords: Java Spring Back-end

Added by randomthinker on Mon, 25 Oct 2021 13:31:19 +0300