Spring的IOC

目录:
Spring简介
Spring的set注入
Spring的自动装配
tomcat管理Spring

Spring简介

什么是spring,它能够做什么?
Spring是一个**开源框架,**它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。

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

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

目的:解决企业应用开发的复杂性
功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
范围:任何Java应用

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

当然,我们说这么多也是为了强调Spring的重要性,其次我们也可以认为Spring是一个中间层框架,万能胶,在这里我们主要来讲**Spring是一个轻量级的控制反转(IoC)**这方面
那么什么是控制反转(或依赖注入)呢?
控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
实质:
将以前由程序员实例化对象/赋值的工作交给了spring处理
案例:实现Spring的IoC
→→→

Spring的set注入

情境导入:

按照以往模式,我们会发现有一个弊端:
当需求变化非常快的时候,不便于维护,因为维护的权利是属于程序员的
spring的ioc就是解决这一问题的
将维护代码的权利由程序员转交给spring容器来完成

现在就和大家讲一讲案例,首先在我们的准备工作完成以后,我们还要下载一个Spring插件,
spring tool suite(下面有链接)
spring tool suite官方下载地址
很详细的网文在线安装介绍
完成这个步骤后,我们就可以配置一下spring-context.xml
当然我们是按照下面这个规则来配置的:

 3.1 id:在容器中查找Bean的id(唯一、且不能以/开头)
   3.2 class:bean的完整类名
   3.3 name:在容器中查找Bean的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
   3.4 scope:(singleton|prototype)默认是singleton
     3.4.1 singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
     3.4.2 prototype(原型模式/多例模式):一个bean定义对应多个对象实例
   3.4 abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
   3.5 parent:指定一个父bean(必须要有继承关系才行)
   3.6 init-method:指定bean的初始化方法
   3.7 constructor-arg:使用有参数构造方法创建javaBean

spring管理Bean的方式,(注入方式)
set注入

  • 基本数据类型
  • 引用数据类型

基本数据类型
**实体类:**这里强调要重写set方法

package com.ly.ioc.web;

import java.util.ArrayList;
import java.util.List;

import com.ly.ioc.biz.UserBiz;
public class UserAction {
	private UserBiz userBiz ;
	private int uid;
	private String uname;
	private List<String> hobby = new ArrayList<String>();
	
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	
	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;
	}
	/**
	 * set注入
	 */
	public void test1() {
		System.out.println("uid:"+this.uid);
		System.out.println("uname:"+this.uname);
		System.out.println("hobby:"+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: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">
	<bean id="userAction"  class="com.ly.ioc.web.UserAction">
<property name="uid" value="22"></property>
 <property name="uname" value="zs"></property> 
		<property name="hobby">
			<list>
				<value>篮球</value>
				<value>RAP</value>
				<value>靖港</value>
			</list>
		</property>
	</bean>
</beans>

配置里面,强调property属性,参见上面配置规则
完成以上步骤,我们set注入就OK了,
再去调用:

package com.ly.ioc.test;

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

import com.ly.ioc.web.UserAction;

/**
 * 模拟浏览器发请求请求后台
 * @author Administrator
 *
 */
public class Demo1 {
public static void main(String[] args) {
	ApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
	UserAction bean = (UserAction)context.getBean("userAction");
//	bean.test1();
	bean.test3();
}
}

引用数据类型
引用注入实质就是spring配置不同,它把接口或者类直接注入配置文件,

/**
	 * 测试引用数据类型
	 */
	public void test3() {
		userBiz.read();
	}

spring-context.xml:

<bean id="userBiz"  class="com.ly.ioc.biz.impl.UserBizImpl1"></bean>
<property name="userBiz" ref="userBiz"></property> 

2、构造注入
我们在上面的实体类中,去掉set方法,再写有参无参构造方法,通过构造函数将值注入配置文件中,

public UserAction() {
	super();
}

	public UserAction(int uid, String uname) {
	super();
	this.uid = uid;
	this.uname = uname;
}
/**
	 * 构造注入
	 */
	public void test2() {
			
		}

配置spring-context.xml:

<constructor-arg name="uid" value="22"></constructor-arg>
<constructor-arg name="uname" value="zs"></constructor-arg>

3、自动装配
自动装配是我们spring-IOC常用的一种模式,
它他可以更准确,无误的达成我们的优化目的。
它有几种供我们选择:其中当我们
default-autowire="byType"的时候,是通过我们的类的接口去找,但当我们有多个类,有一样的接口的话,就会出错。
于是我们就default-autowire=“byName”,根据唯一的IDname去找,

<?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"
	default-autowire="byName"
	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">
	
		<bean id="userBiz" class="com.ly.ioc.biz.UserBizImpl1"></bean>
		<bean id="userBiz2" class="com.ly.ioc.biz.UserBizImpl2"></bean>
</beans>


两个接口:

package com.ly.ioc.biz.impl;

import com.ly.ioc.biz.UserBiz;

public class UserBizImpl1 implements UserBiz {

	@Override
	public void read() {
		System.out.println("加bufferedreader提升性能");
		System.out.println("死记硬背!!!");
	}

}

package com.ly.ioc.biz.impl;

import com.ly.ioc.biz.UserBiz;

public class UserBizImpl2 implements UserBiz {

	@Override
	public void read() {
		System.out.println("边学习边记笔记,最后举一反三");
	}

}

在和上面通用的步骤,调用test方法,我们可以打印出我们所对应的接口的代码。

tomcat管理Spring*

情景导入:

如何将spring的上下文交给tomcat上下文进行管理

  • 首先spring的上下文为什么交给tomcat?
  • 分析:目前工程中的所有javabean都交给了Spring进行管理,那么浏览器发送请求
  • 请求的是tomcat,由tomcat来处理请求,tomcat处理请求一般来说都要访问数据库
  • 数据库是由Dao层访问的,Dao层的实现类又是交给了Spring的上下文管理。那就意味着
  • tomcat要处理请求,必须拿到Spring的上下文,才能够拿到Dao层的javabean

SpringLoadListeren:

package com.ly.ioc.test;

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;
/**
 * 2.如何将spring的上下文交给tomcat上下文进行管理
 * 首先spring的上下文为什么交给tomcat?
 * 分析:目前工程中的所有javabean都交给了Spring进行管理,那么浏览器发送请求
 * 请求的是tomcat,由tomcat来处理请求,tomcat处理请求一般来说都要访问数据库
 * 数据库是由Dao层访问的,Dao层的实现类又是交给了Spring的上下文管理。那就意味着
 * tomcat要处理请求,必须拿到Spring的上下文,才能够拿到Dao层的javabean
 * @author Administrator
 *
 */
@WebListener
public class SpringLoadListener implements ServletContextListener {
	private String springXmlLocation = "";
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("监听了tomcat的启动。。。");
		ServletContext servletContext = sce.getServletContext();
		springXmlLocation = servletContext.getInitParameter(springXmlLocation);
		if(null == springXmlLocation || "".equals(springXmlLocation)) {
			springXmlLocation = "/spring-context.xml";
		}
		System.out.println("springXmlLocation:"+springXmlLocation);
		ApplicationContext springcontext = new ClassPathXmlApplicationContext("/spring-context.xml");
		servletContext.setAttribute("SPRING_CONTEXT_KEY", springcontext);
		
	}

}

Userservlet:

package com.ly.ioc.test;

import java.io.IOException;

import javax.servlet.ServletContext;
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 com.ly.ioc.web.UserAction;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
@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 {
	ServletContext servletContext = req.getServletContext();
	ApplicationContext springContext = (ApplicationContext) servletContext.getAttribute("SPRING_CONTEXT_KEY");
	UserAction bean = (UserAction) springContext.getBean("userAction");
	bean.test3();
}
}

在上面的SpringLoadListeren里,我们做了一个判断,如果没有配置spring的话,我们无妨,当然为了防止配置冲突,我们可以更换配置,
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>

我们就可以获取我们的Spring上下文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值