Spring framework and Ioc (inversion of control) & three parameter transfer methods of Spring & the integration of spring and tomcat

Keywords: Java Eclipse Maven Spring

Foreword: the knowledge to share today is the Spring framework

The code word is not easy. Give me a praise

Reprint, please explain!

Development tool: eclipse

catalogue

Spring framework overview

① What is the Spring framework

② Advantages of Spring framework

③ Spring architecture  

Ioc (control reversal) and cases

Three Spring parameters

① Set pass parameter

② Structural parameters

Integration of Spring and tomcat

① Listener

② Configuring listeners in web.xml  

③ Operation results

Spring framework overview

① What is the Spring framework

Spring is an open source framework. Spring is a lightweight java development framework rising in 2003. It is derived from some concepts and prototypes described by Rod Johnson in his book expert one on one J2EE development and design. It is created to solve the complexity of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows users to choose which component to use, and provides an integrated framework for J2EE 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. The core of spring is inversion of control (IoC) and aspect oriented (AOP). Simply put, spring is a layered Java Se / EE full stack (one-stop) lightweight open source framework.

② Advantages of Spring framework

  • Convenient decoupling and simplified development (high cohesion and low coupling)
    Spring is a big factory (container), which can create all objects and maintain dependencies, and hand them over to spring for management
    spring factories are used to generate bean s
  • AOP programming support
    Spring provides aspect oriented programming, which can easily realize the functions of permission interception, operation monitoring and so on
  • Declarative transaction support
    Transaction management can be completed through configuration without manual programming
  • Facilitate program testing
    Spring supports Junit4. You can easily test spring programs through annotations
  • Convenient integration of various excellent frameworks
    Spring does not exclude various excellent open source frameworks. It provides direct support for various excellent frameworks (such as Struts, Hibernate, MyBatis, Quartz, etc.)
  • Reduce the difficulty of using Java EE API
    Spring provides encapsulation for some APIs (JDBC, JavaMail, remote call, etc.) that are very difficult to use in Java EE development, which greatly reduces the difficulty of applying these APIs

③ Spring architecture  

 

Ioc (control reversal) and cases

inversion of control, which transfers the power of object creation to the framework, is an important feature of the framework, which greatly reduces the coupling. Note that the coupling is not completely eliminated. In vernacular, the container controls the (dependency) relationship between programs, rather than directly controlled by program code in traditional implementation. This is where the so-called "control reversal" concept lies: (dependency) the control right is transferred from the application code to the external container. The transfer of control right is the so-called reversal

Entry case: implementing ioc in Spring

Requirement: simulation upload function

Implement according to the previous operation. If it needs to be rectified or upgraded suddenly

For example: 1. Limit the size of uploaded files     2. Limit upload file category

Trouble encountered: 1. The updated version needs to change the original code
                            2. There is a huge risk associated with the modules that call this method

Using Ioc operation: the work of instantiating / assigning objects previously by programmers is handed over to spring

Import the spring core configuration file spring-context.xml: it is usually modified in this file, which solves the trouble of previous method operations
① New maven project

② Inject dependencies into the 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.zw</groupId>
  <artifactId>zw_Spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>zw_Spring 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>zw_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>

③ Write interface and implement interface (original method and improved method)  

Interface for upload function UserBiz

package com.hpw.ioc.biz;

public interface UserBiz {

	public void upload();
	
}

Implement interface UserBizImpl1 (original version)

package com.hpw.ioc.biz.impl;

import com.hpw.ioc.biz.UserBiz;

/**
 * Function: upload function 
 * Propose rectification: 1. Limit the size of uploaded files 2. Limit the category of uploaded files
 * 
 * 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
 * @author zjjt
 *
 */
public class UserBizImpl1 implements UserBiz {

	@Override
	public void upload() {
		System.out.println("Follow the rules and develop the functions");
	}

	
}

Implement interface UserBizImpl2 (improved version)

package com.hpw.ioc.biz.impl;

import com.hpw.ioc.biz.UserBiz;

/**
 * Function: upload function 
 * Propose rectification: 1. Limit the size of uploaded files 2. Limit the category of uploaded files
 * 
 * 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
 * @author zjjt
 *
 */
public class UserBizImpl2 implements UserBiz {

	@Override
	public void upload() {
		System.out.println("Make conditional judgment and limit. If the file is too large, it cannot be uploaded");
		System.out.println("Follow the rules and develop the functions");
	}

	
}

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

At the same time, there is a huge risk associated with the modules that call this method

  ④ spring writing

Enter the core configuration file and put it under resources (spring-context.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: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,At present Spring unified management  
-->
<!-- <bean class="com.hpw.ioc.biz.impl.UserBizImpl1" name="userBiz1"></bean> -->
<bean class="com.hpw.ioc.biz.impl.UserBizImpl2" name="userBiz1"></bean>
<bean class="com.hpw.ioc.biz.impl.UserBizImpl2" name="userBiz2"></bean>
<bean class="com.hpw.ioc.web.PersonAction" name="personAction">
<property name="userBiz" ref="userBiz2"></property>
</bean>
<bean class="com.hpw.ioc.web.UserAction" name="userAction">
<property name="userBiz" ref="userBiz1"></property>
</bean>
<bean class="com.hpw.ioc.web.UserAction2" name="userAction2">
<property name="userBiz" ref="userBiz1"></property>
</bean>
<bean class="com.hpw.ioc.web.UserAction3" name="userAction3">
<property name="userBiz" ref="userBiz1"></property>
</bean>
</beans>

Modify PersonAction

package com.hpw.ioc.web;

import com.hpw.ioc.biz.UserBiz;
import com.hpw.ioc.biz.impl.UserBizImpl2;


public class PersonAction {

	
	//	Original writing
    //	private UserBiz userBiz=new UserBizImpl2();
	
    //	spring writing

	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}

	public void upload() {
		userBiz.upload();
	}
	
	public static void main(String[] args) {
		PersonAction personAction = new PersonAction();
		personAction.upload();
	}
}

  test

package com.hpw.ioc.test;

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

import com.hpw.ioc.web.ParamAction;
import com.hpw.ioc.web.PersonAction;
import com.hpw.ioc.web.UserAction;
import com.hpw.ioc.web.UserAction2;
import com.hpw.ioc.web.UserAction3;

public class IocTest {

    public static void main(String[] args) {
		//Model spring-context.xml
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		PersonAction personAction = (PersonAction) applicationContext.getBean("personAction");
	    personAction.upload();
		
    }
	
}

Operation results

  When the ref attribute is userBiz2

<bean class="com.hpw.ioc.web.PersonAction" name="personAction">
<property name="userBiz" ref="userBiz2"></property>
</bean>

 

   When the ref attribute is userBiz1

<bean class="com.hpw.ioc.web.PersonAction" name="personAction">
<property name="userBiz" ref="userBiz1"></property>
</bean>

If you want to update the version, directly change userBiz1 to userBiz2,

If the update is wrong, return the new version userBiz2 to the previous version userBiz1

You don't need to change the original code

Three Spring parameters

 * 1.Set parameters
 * 2. Structural parameters
 * 3. Automatic assembly (basically not used)

Demonstrate the first two

① Set pass parameter

ParamAction 

package com.hpw.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 class="com.hpw.ioc.web.ParamAction" name="paramAction">
    <property name="name" value="Zhang San"></property>
    <property name="age" value="20"></property>
    <property name="hobby">
    <list>
      <value>wash</value>
      <value>cut</value>
      <value>blow</value>
    </list>
    </property>
</bean>

Test and operation results

package com.hpw.ioc.test;

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

import com.hpw.ioc.web.ParamAction;
import com.hpw.ioc.web.PersonAction;
import com.hpw.ioc.web.UserAction;
import com.hpw.ioc.web.UserAction2;
import com.hpw.ioc.web.UserAction3;

public class IocTest {

    public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");		
		ParamAction paramAction = (ParamAction) applicationContext.getBean("paramAction");
        paramAction.execute();
    }
	
}

 

② Structural parameters

ParamAction

package com.hpw.ioc.web;

import java.util.List;

public class ParamAction {

	private int age;
	private String name;
	private List<String> hobby;
	
	public ParamAction() {
		super();
	}
	
	public ParamAction(int age, String name, List<String> hobby) {
		super();
		this.age = age;
		this.name = name;
		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 class="com.hpw.ioc.web.ParamAction" name="paramAction">
   <constructor-arg name="name" value="Li Si"></constructor-arg>
    <constructor-arg name="age" value="30"></constructor-arg>
    <constructor-arg name="hobby">
    <list>
    <value>eat</value>
    <value>drink</value>
    <value>sleep</value>
    </list>
    </constructor-arg> 
</bean>

  Test and operation results

package com.hpw.ioc.test;

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

import com.hpw.ioc.web.ParamAction;
import com.hpw.ioc.web.PersonAction;
import com.hpw.ioc.web.UserAction;
import com.hpw.ioc.web.UserAction2;
import com.hpw.ioc.web.UserAction3;

public class IocTest {

    public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");		
		ParamAction paramAction = (ParamAction) applicationContext.getBean("paramAction");
        paramAction.execute();
    }
	
}

 

Integration of Spring and tomcat

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

Every time a javabean is modeled, the longer it takes, the worse its performance will be. Therefore, put the modeling into the listener

① Listener

SpringLoaderListener class implementation   ServletContextListener interface

package com.hpw.ioc.listener;

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) {
	System.out.println("Listener method execution......");
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	sce.getServletContext().setAttribute("SpringContext", applicationContext);
	
	}
	

	
}

② 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>
	<!-- Configure listener -->
	<listener>
		<listener-class>com.hpw.ioc.listener.SpringLoaderListener</listener-class>
	</listener>
</web-app>

③ Operation results

UserServlet 

package com.hpw.ioc.web;

import java.io.IOException;

import javax.servlet.ServletException;
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
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ApplicationContext springContext = (ApplicationContext) req.getServletContext().getAttribute("SpringContext");
		ParamAction paramAction = (ParamAction) springContext.getBean("paramAction");
		paramAction.execute();
	}

}

Refresh interface  

 

Conclusion: the listener can only execute once, and the result can be executed many times  

  It's over here. You're welcome to give advice  

Posted by prcollin on Thu, 28 Oct 2021 06:54:24 -0700