Spring框架及Ioc(控制反转)&Spring的三种传参方式&Spring与tomcat的整合

前言:今天要分享的知识是Spring框架

码字不易,点个赞

转载请说明!

开发工具:eclipse


目录

Spring框架简述

①什么是Spring框架

②Spring框架的优点

③Spring的体系结构 

Ioc(控制反转)及案例

Spring三种传参

①Set传参

②构造传参

Spring与tomcat的整合

①监听器

②web.xml中配置监听器 

③运行结果


Spring框架简述

①什么是Spring框架

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。Spring的核心是控制反转(IoC)和面向切面(AOP)。简单来说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架。

②Spring框架的优点

  • 方便解耦,简化开发 (高内聚低耦合)
    Spring就是一个大工厂(容器),可以将所有对象创建和依赖关系维护,交给Spring管理
    spring工厂是用于生成bean
  • AOP编程的支持
    Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
  • 声明式事务的支持
    只需要通过配置就可以完成对事务的管理,而无需手动编程
  • 方便程序的测试
    Spring对Junit4支持,可以通过注解方便的测试Spring程序
  • 方便集成各种优秀框架
    Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持
  • 降低JavaEE API的使用难度
    Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低

③Spring的体系结构 

Ioc(控制反转)及案例

inversion of control,把对象创建的权力交给框架,是框架的重要特征,大幅度降低了耦合。注意不是完全的消除耦合,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转

入门案例:实现Spring中的ioc

需求:模拟上传功能

按照以前的操做去实行,如果突然需要整改或升级

如:1、限定上传文件大小    2、限定上传文件类别

所遇到的麻烦:1、更新版本需要改动原有代码
                           2、相关调用此方法的模块伴随着巨大的风险

使用Ioc操作:将以前由程序员实例化对象/赋值的工作交给了spring处理

导入spring的核心配置文件spring-context.xml:一般就在该文件中进行修改,解决了以前方法操作的麻烦
①新建maven项目

②注入依赖到pom.xml文件中

<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、导入spring依赖 -->
        <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>

③写接口并实现接口(原始方法,以及改进的的方法) 

上传功能的接口UserBiz

package com.hpw.ioc.biz;

public interface UserBiz {

	public void upload();
	
}

实现接口UserBizImpl1 (原始版本)

package com.hpw.ioc.biz.impl;

import com.hpw.ioc.biz.UserBiz;

/**
 * 功能 : 上传功能 
 * 提出整改: 1.限定上传文件大小 2.限定上传文件类别
 * 
 * 总结:
 * 1.更新版本需要改动原有代码
 * 2.相关调用此方法的模块伴随着巨大的风险
 * action1 需要加限制
 * action2 不需要加限制
 * @author zjjt
 *
 */
public class UserBizImpl1 implements UserBiz {

	@Override
	public void upload() {
		System.out.println("循规蹈矩把功能开发出来");
	}

	
}

实现接口UserBizImpl2(改进后版本)

package com.hpw.ioc.biz.impl;

import com.hpw.ioc.biz.UserBiz;

/**
 * 功能 : 上传功能 
 * 提出整改: 1.限定上传文件大小 2.限定上传文件类别
 * 
 * 总结:
 * 1.更新版本需要改动原有代码
 * 2.相关调用此方法的模块伴随着巨大的风险
 * action1 需要加限制
 * action2 不需要加限制
 * @author zjjt
 *
 */
public class UserBizImpl2 implements UserBiz {

	@Override
	public void upload() {
		System.out.println("做条件判断加限定,文件太大的不能上传");
		System.out.println("循规蹈矩把功能开发出来");
	}

	
}

如果有100个需要整改模块,那就需要改100次原有代码(繁琐);

同时,相关调用此方法的模块伴随巨大的风险

 ④spring写法

考入核心配置文件放到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">

<!-- 
         本文件中配置整个项目中包含的所有的Javabean,目前在于Spring统一管理 
-->
<!-- <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>

修改PersonAction

package com.hpw.ioc.web;

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


public class PersonAction {

	
	//	原始写法
    //	private UserBiz userBiz=new UserBizImpl2();
	
    //	spring写法

	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();
	}
}

 测试

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) {
		//对spring-context.xml进行建模
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		PersonAction personAction = (PersonAction) applicationContext.getBean("personAction");
	    personAction.upload();
		
    }
	
}

运行结果

 当ref属性为userBiz2时

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

 

  当ref属性为userBiz1时

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

如果是要更新版本直接将userBiz1改为userBiz2,

如果更新错误将新版本userBiz2退回上一版本userBiz1

即可,不需要改动原本代码

Spring三种传参

 * 1.Set传参
 * 2.构造传参
 * 3.自动装配(基本不用)

论证前两种

①Set传参

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);
	}

}

配置(spring-context.xml)

<bean class="com.hpw.ioc.web.ParamAction" name="paramAction">
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="hobby">
    <list>
      <value>洗</value>
      <value>剪</value>
      <value>吹</value>
    </list>
    </property>
</bean>

测试及运行结果

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();
    }
	
}

 

②构造传参

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);
	}
	
}

 配置(spring-context.xml)

<bean class="com.hpw.ioc.web.ParamAction" name="paramAction">
   <constructor-arg name="name" value="李四"></constructor-arg>
    <constructor-arg name="age" value="30"></constructor-arg>
    <constructor-arg name="hobby">
    <list>
    <value>吃</value>
    <value>喝</value>
    <value>睡</value>
    </list>
    </constructor-arg> 
</bean>

 测试及运行结果

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();
    }
	
}

 

Spring与tomcat的整合

假如spring-context.xml中配置了几百个类,测试建模的时间过程非常久;

javabean每建一次模,时间就越久,性能就越差,所以将建模放到监听器中

①监听器

SpringLoaderListener类实现 ServletContextListener接口

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("监听器方法执行......");
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	sce.getServletContext().setAttribute("SpringContext", applicationContext);
	
	}
	

	
}

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

③运行结果

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();
	}

}

刷新界面 

 

结论:监听器只会执行一次,结果可执行多次 

 到这里就结束了,欢迎大佬指点 

猜你喜欢

转载自blog.csdn.net/weixin_56069070/article/details/120889773