spring之ioc

spring之ioc

1. 什么是spring,它能够做什么?
Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。
Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。
然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
目的:解决企业应用开发的复杂性
功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
范围:任何Java应用
简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.1 中间层框架、万能胶
struts2
spring
hibernate
1.2 容器框架
JavaBean 项目中的一个个类
IOC和AOP

配置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>T237_spring</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>T237_spring Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.44</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		<!-- 导入spring依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.10.RELEASE</version>
		</dependency>


	</dependencies>
	<build>
		<finalName>T237_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>

两种安装方式:

第一张:本地安装进入Install New Software 点击add把硬盘里解压好的文件放入里面 :
在这里插入图片描述

第二种:eclipse在线下载 进入 Eclips Marketplace下载 Spring IDE Roo Surpot:
在这里插入图片描述
安装好之后配置xml文件:

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


</beans>

通过企业的案例来讲解使用spring IOC的必要性
v1.0:实现游戏的上传功能
v2.0:对游戏的上传进行功能优化

UserBiz 接口:

package com.xiaoyi.ioc.biz;

/**通过企业的案例来讲解使用spring IOC的必要性
 * v1.0:实现游戏的上传功能
 * v2.0:对游戏的上传进行功能游戏
 * @author Administrator
 *
 */
public interface UserBiz {
public void upload();
}

UserBizImpl1:

package com.xiaoyi.ioc.impl;

import com.xiaoyi.ioc.biz.UserBiz;
/**
 * 实现userBiz接口
 * @author Administrator
 *
 */
public class UserBizImpl1 implements UserBiz {

	@Override
	public void upload() {
		//System.out.println("开始优化性能的代码");
        System.out.println("实现用户上传的功能");		
	}

}

UserBizImpl2:

package com.xiaoyi.ioc.impl;

import com.xiaoyi.ioc.biz.UserBiz;
/**
 * 实现userBiz接口
 * @author Administrator
 *
 */
public class UserBizImpl2 implements UserBiz {

	@Override
	public void upload() {
		System.out.println("开始优化性能的代码");
        System.out.println("实现用户上传的功能");		
	}

}

UserAction调用版本2(new UserBizImpl2 也可以换成版本1 UserBizImpl1)性能不好,很麻烦

package com.xiaoyi.ioc.web;

import com.xiaoyi.ioc.biz.UserBiz;
import com.xiaoyi.ioc.impl.UserBizImpl1;
import com.xiaoyi.ioc.impl.UserBizImpl2;

public class UserAction {
	//调用
	public UserBiz userBiz=new UserBizImpl2();
	public void upload() {
		userBiz.upload();
	}

}

IocTest 测试:

package com.xiaoyi.ioc.test;

import com.xiaoyi.ioc.web.UserAction;

public class IocTest {
	//测试
public static void main(String[] args) {
	UserAction userAction=new UserAction();
	userAction.upload();
}
}

版本1:
在这里插入图片描述
版本2:
在这里插入图片描述

使用IOC方法:

UserAction 定义属性,提供set get方法:

package com.xiaoyi.ioc.web;

import com.xiaoyi.ioc.biz.UserBiz;

public class UserAction {
	//调用
	//IOC方法定义属性,提供set get方法
	public UserBiz userBiz;
	
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	
	public void upload() {
		userBiz.upload();
	}
}

OrderAction:

package com.xiaoyi.ioc.web;

import com.xiaoyi.ioc.biz.UserBiz;

public class OrderAction {
	//调用
	//IOC方法定义属性,提供set get方法
	public UserBiz userBiz;
	
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	
	public void upload() {
		userBiz.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: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">
<!--版本二的路径和id  -->
<bean class="com.xiaoyi.ioc.impl.UserBizImpl2" id="userBiz"></bean>
<bean class="com.xiaoyi.ioc.web.UserAction" id="hhh">
<!-- 
name:里面填的是useraction里面的属性
ref:里面填上面对应的id
 -->
<property name="userBiz" ref="userBiz"></property>
</bean>


<bean class="com.xiaoyi.ioc.web.OrderAction" id="ttt">
<property name="userBiz" ref="userBiz"></property>
</bean>


</beans>

IocTest测试:

package com.xiaoyi.ioc.test;

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

import com.xiaoyi.ioc.web.OrderAction;
import com.xiaoyi.ioc.web.UserAction;

public class IocTest {
	//测试
public static void main(String[] args) {
	/*UserAction userAction=new UserAction();
	userAction.upload();*/
	//ioc方法测试
ApplicationContext springContext = new ClassPathXmlApplicationContext("/spring-context.xml");

UserAction userAction =  (UserAction) springContext.getBean("hhh");
OrderAction orderAction =  (OrderAction) springContext.getBean("ttt");
//两个上传
userAction.upload();
orderAction.upload();

}
}

结果都是版本2 因为在spring-context.xml里面配置的是版本2结果就是版本2.一处改动,多处受影响。不需要跟之前一样每个action都要改:
在这里插入图片描述

set注入:

UserAction:

package com.xiaoyi.ioc.web;

import java.util.List;

import com.xiaoyi.ioc.biz.UserBiz;

/**IOC的注入方式及各类值类型:
 * set注入
 *    基本类型与String
 *    数组
 *    自定义类型(刚刚写过了)
 *    
 *    
 * 构造注入
 * 自动装配
 * 
 * @author Administrator
 *
 */
public class UserAction {
	//调用
	//IOC方法定义属性,提供set get方法
	public UserBiz userBiz;
	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 UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	
	public void upload() {
		userBiz.upload();
	}
	//测试方法:值是否进来
	/**set注入问题
	 * 
	 */
	public void test1() {
System.out.println(this.uname);
System.out.println(this.age);
System.out.println(this.hobby);
	}
}

spring-context.xml配置:

<!--set注入用 property标签 -->
<property name="userBiz" ref="userBiz"></property>
<property name="uname" value="yiyi"></property>
<property name="age" value="19"></property>
<property name="hobby">
<list>
<value>吃饭</value>
<value>睡觉</value>
<value>玩手机</value>

</list>

</property>

测试里面调用直接调用就行了

package com.xiaoyi.ioc.test;

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

import com.xiaoyi.ioc.web.OrderAction;
import com.xiaoyi.ioc.web.UserAction;

public class IocTest {
	//测试
public static void main(String[] args) {
	/*UserAction userAction=new UserAction();
	userAction.upload();*/
	//ioc方法测试
ApplicationContext springContext = new ClassPathXmlApplicationContext("/spring-context.xml");

UserAction userAction =  (UserAction) springContext.getBean("hhh");
OrderAction orderAction =  (OrderAction) springContext.getBean("ttt");
//两个上传
/*userAction.upload();
orderAction.upload();
*/
//set注入测试:
userAction.test1();


}
}

结果:
在这里插入图片描述

构造注入:

UserAction (把uname和age的setget方法给注释掉,运行时就会报错,使用构造方法在spring-context.xml里面配置就可以使用):

package com.xiaoyi.ioc.web;

import java.util.List;

import com.xiaoyi.ioc.biz.UserBiz;

/**IOC的注入方式及各类值类型:
 * set注入
 *    基本类型与String
 *    数组
 *    自定义类型(刚刚写过了)
 *    
 *    
 * 构造注入
 * 
 * 自动装配
 * 
 * @author Administrator
 *
 */
public class UserAction {
	//调用
	//IOC方法定义属性,提供set get方法
	public UserBiz userBiz;
	private String uname;
	private int age;
	private List<String> hobby;
	
	//构造注入:提供一个有参无参构造器
	public UserAction(String uname, int age) {
		super();
		this.uname = uname;
		this.age = age;
	}
	
	public UserAction() {
		super();
	}

	public List<String> getHobby() {
		return hobby;
	}
	public void setHobby(List<String> hobby) {
		this.hobby = hobby;
	}
	
	
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	
	public void upload() {
		userBiz.upload();
	}
	//测试方法:值是否进来
	/**set注入问题
	 * 
	 */
	public void test1() {
System.out.println(this.uname);
System.out.println(this.age);
System.out.println(this.hobby);
	}
}

spring-context.xml配置构造注入:

<!--构造注入用 constructor-arg -->
<constructor-arg name="uname" value="lala"></constructor-arg>
<constructor-arg name="age" value="20"></constructor-arg>

结果:
在这里插入图片描述

自动装配:

在spring-context.xml配置里面加一个byType:
在这里插入图片描述
在上面加完buType之后,每个action都不再需要加下面这一行代码了:

<!--使用bytype之后每个action配置里面就不需要他了  -->
<!-- <property name="userBiz" ref="userBiz"></property> -->

在spring-context.xml配置里面加一个byName:
在这里插入图片描述
byName和byType的区别:

<!--
bytype:中 id里面属性随便是什么都没事 
byName:中的id中名字要跟Useraction定义的属性名一样就不会报错
-->
<bean class="com.xiaoyi.ioc.impl.UserBizImpl1" id="userBiz"></bean>

结果都是调用的版本1的:
在这里插入图片描述

监听器:

SpringLoaderLister:

package com.xiaoyi.ioc.listenter;

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

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

/**
 * spring 作为管理整个工程中的所有JavaBean,那么如何在用户发送请求的时候能够
 * 访问到指定的JavaBean?
 * 处理方式:
 * 		监听器中将spring的上下文交给tomcat的上下文中进行管理
 * 		浏览器请求-->request-->servletContext-->springContext-->任意的JavaBean
 * @author 10570
 *
 */
@WebServlet("/user")
public class SpringLoaderLister implements ServletContextListener{

	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("tomact启动就触发..");
		//tomact上下文
		ServletContext tomactContext = sce.getServletContext();

		String springXmlLocation = tomactContext.getInitParameter("springXmlLocation"); 
		System.out.println("spring的上下文配置文件:"+springXmlLocation);
		ApplicationContext springContext = null;
		if(springXmlLocation == null || "".equals(springXmlLocation)) {
			//拿到spring上下文
     springContext= new ClassPathXmlApplicationContext("/spring-context.xml");	
		
		}else {
 springContext= new ClassPathXmlApplicationContext(springXmlLocation);	

		}
	tomactContext.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>
   <!-- 从监听器里面传过来 -->
  <!--<listener>
  <listener-class>com.xiaoyi.ioc.listenter.SpringLoaderLister</listener-class>
  </listener> -->
  <context-param>
  <param-name>springXmlLocation</param-name>
  <param-value>/spring-other.xml</param-value>
  </context-param>
  
  
</web-app>

UserServlet:

package com.xiaoyi.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("/demo")
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");
System.out.println(springContext);
UserAction userAction =  (UserAction) springContext.getBean("hhh");
userAction.upload();





}
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值