Spring——IOC

目录

一、对Spring的理解

二、Spring中IOC的特点

三、依赖注入的3种方式

四、Spring与web容器的整合

五、总结


一、对Spring的理解

1、Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。

Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。

   然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。

   目的:解决企业应用开发的复杂性

   功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能

   如下图(Spring所包含的功能):

   范围:任何Java应用

   简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架

 1.1 Spring是中间层框架、万能胶


       struts2
       spring
       hibernate

在Spring 出现之前,框架之间都必须相互整合:

 而Spring出现之后,各框架只需要跟Spring整合即可:

   1.2 容器框架


         JavaBean    项目中的一个个类
         IOC和AOP
        

二、Spring中IOC的特点

首先新建一个maven项目,注意要先导入jar依赖:

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.zking</groupId>
  <artifactId>T280_spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>T280_spring Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!-- 将当前项目所用的jar包依赖版本定义在外部,目的在于所有jar包版本进行统一 管理-->
  <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>T280_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>

web.xml:

<!-- 修改web.xml由2.3至3.1 -->
<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">

项目创建成功之后呢,我们开始我们伟大的编码工程:

关于Spring中IOC的特点,我们拿一个 用户业务类来作为案例,

比如说有客户,它提出需求:同时在用户模块、订单模块拿到所有的用户数据

需求总是会有所变更,

需求变更1:
     同时在用户模块、订单模块拿到所有的用户数据,并且要求用户数据是已经通过
年龄排序了的。
     对应策略:修改userBiz中的list方法,添加排序功能,按照年龄排序
 
 需求变更2:
     同时在用户模块、订单模块拿到所有的用户数据,并且要求用户数据是已经通过
注册的时间点排序了的。
     对应策略:修改userBiz中的list方法,添加排序功能,按照时间点排序

总结:

以上的对应策略是我们最原始的方法,弊端:频繁修改业务层biz层代码

同时还有一个多实现方法,弊端:凡是涉及到用户业务层调用的地方,都需要修改代码

因此我们的SpringIOC就来了:

biz层:

 UserBiz:

package com.ycx.biz;
/**
 * 用户业务类
 * @author 杨总
 *
 */
public interface UserBiz {
	void list();
}

 web层:

UserAction :

package com.ycx.web;

import com.ycx.biz.UserBiz;
import com.ycx.biz.impl.UserBizImpl1;
import com.ycx.biz.impl.UserBizImpl2;

public class UserAction {
//	private UserBiz userBiz=new UserBizImpl1();
	
	private UserBiz userBiz;
	

	public UserBiz getUserBiz() {
		return userBiz;
	}


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


	public void list() {
		userBiz.list();
	}
	
	
}

Spring 配置文件:

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">

<!--IOC的主要作用:管理整个项目的javabean,依靠依赖注入、控制反转的特点进行管理  -->
	<!-- <bean class="com.ycx.biz.impl.UserBizImpl2" id="userBiz1"></bean> -->
	<bean class="com.ycx.biz.impl.UserBizImpl2" id="userBiz"></bean>
	<bean class="com.ycx.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz"></property>
	</bean>
	<bean class="com.ycx.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz"></property>
	</bean>
</beans>

 OrderAction :

package com.ycx.web;

import com.ycx.biz.UserBiz;
import com.ycx.biz.impl.UserBizImpl1;
import com.ycx.biz.impl.UserBizImpl2;

public class OrderAction {

//	private UserBiz userBiz=new UserBizImpl1();
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}


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



	public void list() {
		userBiz.list();
	}
}

 实现类:

UserBizImpl1 :

package com.ycx.biz.impl;

import com.ycx.biz.UserBiz;

public class UserBizImpl1 implements UserBiz{

	@Override
	public void list() {
		System.out.println("查询用户数据...通过年龄排序...");
		
	}
	
}

 UserBizImpl2 :

package com.ycx.biz.impl;

import com.ycx.biz.UserBiz;

public class UserBizImpl2 implements UserBiz{

	@Override
	public void list() {
		System.out.println("查询用户数据...通过注册的时间点排序...");
		
	}
	
}

 测试:

package com.ycx.ioc.demo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.UserAction;

public class Demo1 {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction)context.getBean("userAction");
		userAction.list();
	}
}

 打印结果:

 因此,Spring只需要修改配置就好了(以前手动创建对象,Spring可自动创建对象):

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">

<!--IOC的主要作用:管理整个项目的javabean,依靠依赖注入、控制反转的特点进行管理  -->
	<bean class="com.ycx.biz.impl.UserBizImpl1" id="userBiz"></bean>
	<bean class="com.ycx.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz"></property>
	</bean>
	<bean class="com.ycx.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz"></property>
	</bean>
</beans>

 再测试:

package com.ycx.ioc.demo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.OrderAction;
import com.ycx.web.UserAction;
/**
 * 1、对Spring框架的配置进行建模,建模之后,spring-context.xml中所有的javabean信息都会加载进Spring 容器的上下文
 * 2、上下文中包含了spring-context.xml 所有对象
 * @author 杨总
 *
 *IOC的特点(什么叫控制反转):
 *	指的是将创建对象的权利反转给Spring容器来完成
 *
 */
public class Demo1 {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction)context.getBean("userAction");
		userAction.list();
		
		OrderAction orderAction = (OrderAction)context.getBean("orderAction");
		orderAction.list();
	}
}

 

  IOC的特点(什么叫控制反转):
           指的是将创建对象的权利反转给Spring容器来完成

三、依赖注入的3种方式

如果把OrderAction内的get和set方法注释掉,再测试,会报错:

 所以我们来需要了解依赖注入的三种方式。

依赖注入的三种方式:


    1、set注入——在业务类中获取属性的set和get方法

UserAction:

package com.ycx.web;



import java.util.List;

import com.ycx.biz.UserBiz;
import com.ycx.biz.impl.UserBizImpl1;
import com.ycx.biz.impl.UserBizImpl2;
/**
 * 依赖注入的三种方式:
 * 	1、set注入
 * 	2、构造注入
 * 	3、自动装配
 * 		byName
 * 		byType
 * 
 * @author 杨总
 *
 */
public class UserAction {
//	private UserBiz userBiz=new UserBizImpl1();
	private UserBiz userBiz;
	
	
	
	public UserBiz getUserBiz() {
		return userBiz;
	}

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


	private String name;
	private int age;
	private List<String> hobby;
	
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public List<String> getHobby() {
		return hobby;
	}

	public void setHobby(List<String> hobby) {
		this.hobby = hobby;
	}

	public void list() {
		System.out.println(name);
		System.out.println(age);
		System.out.println(hobby);
		userBiz.list();
	}
	
	
}

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">

<!--IOC的主要作用:管理整个项目的javabean,依靠依赖注入、控制反转的特点进行管理  -->
	<bean class="com.ycx.biz.impl.UserBizImpl1" id="userBiz"></bean>
	<bean class="com.ycx.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz"></property>
		
		<property name="name" value="杨总"></property>
		<property name="age" value="22"></property>
		<property name="hobby">
			<list>
				<value>唱歌</value>
				<value>跳舞</value>
				<value>乒乓球</value>
			</list>
		</property>
	</bean>
	<bean class="com.ycx.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz"></property>
	</bean>
</beans>

Demo1:

package com.ycx.ioc.demo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.OrderAction;
import com.ycx.web.UserAction;
/**
 * 1、对Spring框架的配置进行建模,建模之后,spring-context.xml中所有的javabean信息都会加载进Spring 容器的上下文
 * 2、上下文中包含了spring-context.xml 所有对象
 * @author 杨总
 *
 *IOC的特点(什么叫控制反转):
 *	指的是将创建对象的权利反转给Spring容器来完成
 *
 */
public class Demo1 {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
		
		OrderAction orderAction = (OrderAction)context.getBean("orderAction");
		orderAction.list();
	}
}

在Demo1中运行,

打印结果如下:

 

    2、构造注入——在业务类中回去属性的构造方法

OrderAction :

package com.ycx.web;

import java.util.List;

import com.ycx.biz.UserBiz;
import com.ycx.biz.impl.UserBizImpl1;
import com.ycx.biz.impl.UserBizImpl2;

public class OrderAction {

//	private UserBiz userBiz=new UserBizImpl1();
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}


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

	private String name;
	private int age;
	private List<String> hobby;

	
	
	public OrderAction(String name, int age, List<String> hobby) {
		super();
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}

	public OrderAction() {
		super();
	}

	public void list() {
		System.out.println(name);
		System.out.println(age);
		System.out.println(hobby);
		userBiz.list();
	}
}

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">

<!--IOC的主要作用:管理整个项目的javabean,依靠依赖注入、控制反转的特点进行管理  -->
	
	
	<bean class="com.ycx.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz"></property>
		<!-- 构造注入 -->
		<constructor-arg name="name" value="杨总"></constructor-arg>
		<constructor-arg name="age" value="18"></constructor-arg>
		<constructor-arg name="hobby" >
				<list>
					<value>唱歌</value>
					<value>跳舞</value>
					<value>乒乓球</value>
				</list>
		</constructor-arg>
	</bean>
</beans>

然后在Demo1运行:

 

    3、自动装配


                ① byName——是Spring管理的bean对象的id进行查找,如果找不到则注入失败,反之成功

        
               运行:

 

          ②byType——是Spring管理的bean对象接口实现类进行查找,如果没有或两个以上,则注入失败,反之成功。

 

 

四、Spring与web容器的整合

 Spring与web容器的整合过程


 Why: 建模的过程是十分耗时的
 解决问题:
         1、建模必不可少
         2、建模要保证只执行一次
         3、建模后期望在在每一个servlet都能够拿到Spring的上下文对象ClassPathXmlApplicationContext


  How:
         1、监听器的初始化方法
         2、Spring的上下文 要存放在tomacat上下文中

DemoServlet :

package com.ycx.ioc.demo;

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 org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.UserAction;



@WebServlet("/springDemo")
public class DemoServlet extends HttpServlet{
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		ClassPathXmlApplicationContext context =(ClassPathXmlApplicationContext) req.getServletContext().getAttribute("springContext");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
		
		
		super.service(req, res);
	}
}

 SpringLoadListener :

 

 

package com.ycx.ioc.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.UserAction;

public class SpringLoadListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
System.out.println("初始化......");
		//	拿到Spring的上下文
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
//		将Spring上文保存到Tomcat上下文中
		ServletContext servletContext=sce.getServletContext();
		servletContext.setAttribute("springContext", context);
	
	
	}
	
}

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.ycx.ioc.listener.SpringLoadListener</listener-class>
</listener>

</web-app>

运行:

 进一步优化:

 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>

<context-param>
	<param-name>springConfigLocation</param-name>
	<param-value>/applicationContext.xml</param-value>
</context-param>

<listener>
	<listener-class>com.ycx.ioc.listener.SpringLoadListener</listener-class>
</listener>

</web-app>

 SpringLoadListener :

package com.ycx.ioc.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ycx.web.UserAction;

public class SpringLoadListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("初始化......");
		ServletContext servletContext=sce.getServletContext();
		String springConfigLocation = servletContext.getInitParameter("springConfigLocation");
		System.out.println(springConfigLocation+"......");
		//	拿到Spring的上下文
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
//		将Spring上文保存到Tomcat上下文中
		servletContext.setAttribute("springContext", context);
	
	
	}
	
}

五、总结

1、Spring的作用

        容器框架        用来整合其他的第三方框架

        有两大核心组件:IOC和aop

2、IOC的作用

        特点:依赖注入、控制反转

        控制反转:将创建对象的权利,由程序员手动new对象的权利交给Spring容器

        优点:便于维护,拥抱变化

3、依赖注入的方式

        set注入

        构造注入

        自动装配

4、自动装配

        byName:根据bean的id在Spring的上下文进行寻找

        byType:根据属性接口在Spring上下文找对应的接口实现类

5、Spring与web集成

        监听器  初始化  

        优化

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酒醉猫(^・ェ・^)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值