Spring之IOC

1.什么是spring,它能够做什么?

Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
目的:解决企业应用开发的复杂性
功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
范围:任何Java应用

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

2.什么是控制反转(或依赖注入) ?

控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中

简单案例导入思维:
使用spring完成:给客户添加一个文件上传的接口,实现文件上传的功能 客户在使用了之后,觉得上传文件的速度太慢了,要求提升该功能的性能
UserService.java

package com.wangcong.ioc.service;
/**
 * 实现业务功能的接口
 * 完成的需求:给客户添加一个文件上传的接口,实现文件上传的功能
 *  客户在使用了之后,觉得上传文件的速度太慢了,要去提升该功能的性能
 * @author only老K,我为自己带盐
 *
 */
public interface UserService {
  public void upload();
}

UserServiceImpl1.java

package com.wangcong.ioc.service;
/**
 * 第一个版本的:程序员实现功能而写的实现类,并没有考虑到性能问题 
 * @author 86135
 *
 */
public class UserServiceImpl1 implements UserService{

	@Override
	public void upload() {
		//性能不行的话,会在当前方法进行代码修改,比如说,之前没有用到缓冲流,现在在当前方法中使用缓冲流,来提升性能
		 System.out.println("v1.0 程序员实现功能而写的实现类,并没有考虑到性能的问题");		
	}
	
}

UserServiceImpl2.java

package com.wangcong.ioc.service;
/**
 * 解决客户投诉问题,上传功能的性能问题 v2.0
 * @author only老k,我为自己带盐
 *
 */
public class UserServiceImpl2 implements UserService{
	@Override
	public void upload() {
    System.out.println("解决客户投诉问题,上传功能的性能问题 v2.0");
	}
}

UserAction.java

package com.wangcong.web;

import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl1;

public class UserAction {
private UserService  userService=new UserServiceImpl1();

public void test1() {
	userService.upload();
}
}

TeacherAction.java

package com.wangcong.web;

import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl2;

public class TeacherAction {
private UserService userService=new UserServiceImpl2();

public void test1() {
	userService.upload();
}
}

问题:
目前存在问题:如果说多个action类要使用同一个service接口,那么一旦service实现类发生改变那么,就需要程序员改动每一个action中的代码,去改变该service接口的具体应用的实现类。

但是在Springioc就解决上述问题:
实现了一处改动,多处受益的结果

提供项目大体图片:
在这里插入图片描述
提供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>string</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>string 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>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>

上述代码更改两个Action方法即可。
TeacherAction.java

package com.wangcong.web;

import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl2;

public class TeacherAction {
private UserService userService;

public UserService getUserService() {
	return userService;
}

public void setUserService(UserService userService) {
	this.userService = userService;
}

public void test1() {
	userService.upload();
}
}

UserAction.java

package com.wangcong.web;

import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl1;

public class UserAction {
private UserService  userService;

public UserService getUserService() {
	return userService;
}

public void setUserService(UserService userService) {
	this.userService = userService;
}

public void test1() {
	userService.upload();
}
}

编写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:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">
		
<bean class="com.wangcong.ioc.service.UserServiceImpl2" id="userService"></bean>
<bean class="com.wangcong.web.UserAction" id="userAction" >
<property name="userService" ref="userService"></property>
</bean>

<bean class="com.wangcong.web.TeacherAction" id="teacherAction" >
<property name="userService" ref="userService"></property>
</bean>
</beans>

IocTest.java

package com.wangcong.ioc.test;

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

import com.wangcong.web.TeacherAction;
import com.wangcong.web.UserAction;

public class IocTest {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
     ApplicationContext applicationContext
     =new ClassPathXmlApplicationContext("/spring-context.xml");
   UserAction userAction=  (UserAction) applicationContext.getBean("userAction");
   userAction.test1();
   
   TeacherAction teacherAction = (TeacherAction) applicationContext.getBean("teacherAction");
   teacherAction.test1();
	}
}

运行IocTest.java文件
实现效果如下:
在这里插入图片描述
以及更改spring-congtext.xml文件
在这里插入图片描述
结果如下:
在这里插入图片描述
实现每次只需要更改一行代码即可.

Spring的注入方式

 * IOC的注入方式及各类类型
 * set注入
 *    基本数据类型与String
 *    数组
 *    自定义类型
 *    
 * 构造注入
 * 自动装配
 * @author only老K,我为自己带盐

讲解set注入
UserAction.java

package com.wangcong.web;

import java.util.List;


import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl1;
/**
 * IOC的注入方式及各类类型
 * set注入
 *    基本数据类型与String
 *    数组
 *    自定义类型
 *    
 * 构造注入
 * 自动装配
 * @author only老K,我为自己带盐
 *
 */
public class UserAction {
private UserService  userService;
private String uname;
private int age;
private List<String> hobby;

public String getUname() {
	return uname;
}

public void setUname(String uname) {
	this.uname = uname;
}

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 UserService getUserService() {
	return userService;
}

public void setUserService(UserService userService) {
	this.userService = userService;
}
/**
 * 注入问题
 */
public void test1() {
//	userService.upload();
	System.out.println(this.uname);
	System.out.println(this.age);
	System.out.println(this.hobby);
}
}

更改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:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">
		
<bean class="com.wangcong.ioc.service.UserServiceImpl1" id="userService"></bean>
<bean class="com.wangcong.web.UserAction" id="userAction" >
<!-- set注入用property标签 -->
<property name="userService" ref="userService"></property>
 <property name="uname" value="zs" ></property>
 <property name="age" value="22"></property>
 <property name="hobby">
 <list>
 <value>篮球</value>
 <value>Rap</value>
 <value>广场舞</value>
 </list>
 </property>

</bean>

<bean class="com.wangcong.web.TeacherAction" id="teacherAction" >
<property name="userService" ref="userService"></property>
</bean>
</beans>

在Ioctest.java文件中测试结果如下:
在这里插入图片描述
讲解构造注入
提供UserAction.java

package com.wangcong.web;

import java.util.List;


import com.wangcong.ioc.service.UserService;
import com.wangcong.ioc.service.UserServiceImpl1;
/**
 * IOC的注入方式及各类类型
 * set注入
 *    基本数据类型与String
 *    数组
 *    自定义类型
 *    
 * 构造注入
 * 自动装配
 * @author only老K,我为自己带盐
 *
 */
public class UserAction {
private UserService  userService;
private String uname;
private int age;
private List<String> hobby;

public UserAction() {
	super();
}

public UserAction(String uname, int age) {
	super();
	this.uname = uname;
	this.age = age;
}

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

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

public UserService getUserService() {
	return userService;
}

public void setUserService(UserService userService) {
	this.userService = userService;
}
/**
 * 注入问题
 */
public void test1() {
//	userService.upload();
	System.out.println(this.uname);
	System.out.println(this.age);
	System.out.println(this.hobby);
}
}

更改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:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">
		
<bean class="com.wangcong.ioc.service.UserServiceImpl2" id="userService"></bean>
<bean class="com.wangcong.web.UserAction" id="userAction" >
<!-- set注入用property标签 -->
 <property name="userService" ref="userService"></property> 
 <!-- <property name="uname" value="zs" ></property>
 <property name="age" value="22"></property> -->
 <!-- set注入用构造注入 -->
 <constructor-arg name="uname" value="ls"></constructor-arg>
 <constructor-arg name="age" value="22"></constructor-arg>
 <property name="hobby">
 <list>
 <value>篮球</value>
 <value>Rap</value>
 <value>广场舞</value> 
 </list>
 </property>
</bean>

<bean class="com.wangcong.web.TeacherAction" id="teacherAction" >
 <property name="userService" ref="userService"></property>
</bean>
</beans>

测试成功。

讲解自动装配:default-autowire="byType"以及default-autowire=“byName”

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	default-autowire="byType"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">
		
<bean class="com.wangcong.ioc.service.UserServiceImpl2" id="userService"></bean>
<bean class="com.wangcong.web.UserAction" id="userAction" >
<!-- set注入用property标签 -->
<!-- <property name="userService" ref="userService"></property> -->
 <!-- <property name="uname" value="zs" ></property>
 <property name="age" value="22"></property> -->
 <!-- set注入用构造注入 -->
 <constructor-arg name="uname" value="ls"></constructor-arg>
 <constructor-arg name="age" value="22"></constructor-arg>
 <property name="hobby">
 <list>
 <value>篮球</value>
 <value>Rap</value>
 <value>广场舞</value> 
 </list>
 </property>
</bean>

<bean class="com.wangcong.web.TeacherAction" id="teacherAction" >
 <!-- <property name="userService" ref="userService"></property> -->
</bean>
</beans>

spring的上下文交给tomcat上下文管理

UserServlet.java

package com.wangcong.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;
@WebServlet("/user")
public class UserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
}
@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("处理用户请求");
		ApplicationContext springContext = (ApplicationContext) req.getServletContext().getAttribute("spring_key");
		UserAction userAction = (UserAction) springContext.getBean("xxx");
		userAction.upload();
	}

}

SpringLoaderListener.java

package com.wangcong.ioc.listener;

import javax.servlet.ServletContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * spring作为管理整个工程中的所有的javabean,那么如何在用户发送请求的时候能够访问到到指定的javabean
 * @author 86135
 *处理方式:在监听器中将spring的上下文交给tomcat进行管理
 *思路:浏览器-->request-->servletContext-->springContext-->任意的JavaBean
 */
@WebListener
public class SpringLoaderListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("tomcat一启动就触发了");
		//拿到tomcat上下文 
		ServletContext tomcatContext = sce.getServletContext();
		//springXmlLocation来源:web.xml
		String springXmlLocation=tomcatContext.getInitParameter("springXmlLocation");
		System.out.println("spring的上下文配置"+springXmlLocation);
		//可能自定义mvc中没有填配置文件就用默认的
		ApplicationContext springContext =null;
		if(springXmlLocation==null || "".equals(springXmlLocation)) {//没有配置
			 springContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		}else {//配置了
			springContext = new ClassPathXmlApplicationContext(springContext);
		}
		//拿到spring的上下文
		//ApplicationContext springContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		
		//交给tomcat管理
		tomcatContext.setAttribute("spring_key", springContext);
	}

}

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>springXmlLocation</param-name>
  <param-value>/spring-other.xml</param-value>
  </context-param>
</web-app>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值