spring之ioc

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

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

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

什么是控制反转(或依赖注入)
控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
Spring是主要作用体现在:控制反转(IOC)、面向切面(AOP)的容器框架和整合框架的粘合剂,今天我主要解释它的控制反转(IOC)

我们在pom.xml里面配置spring 的依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.10.RELEASE</version>
</dependency>

接下来spring配置文件的创建(spring-context.xml)
可以说spring-context.xml是一个不简单的xml,所以我们可以配置相对应的spring插件
我们要下载spring插件; 我们在eclipse商城里面下载,
如图所示:注意:它下载会很慢的 不过要耐心等待,
在这里插入图片描述
然后进来之后点击Installed,然后进去之后会有一个搜索框,你输入sping
在这里插入图片描述
Spring管理Bean(java文件)的方式(注入方式)
1、set注入
基本数据注入
自定类型注入(我们在开发中常用)

set 注入就比如我建了一个实体类一样,我们要有set,get方法然后就可以了,
当然我们还需要配置spring-context.xml文件

package com.thf.ioc.web;

import java.util.List;

import com.thf.ioc.biz.UserBiz;
import com.thf.ioc.biz.impl.UserBizImpl;
import com.thf.ioc.biz.impl.UserBizImpl2;
/**
 * ioc的注入方式及各类类型   有三种注入方式:
 * 
 * set注入
 * 基本类型与String
 * 数组
 * 自定义类型
 * 
 * 构造注入
 * 自动装配
 * spring4之后出现的
 * byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
 * byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
 * 
 * @author Administrator
 *
 */
public class UserAcion {
      
	private UserBiz userBiz;//自定义类型
	private String uname;
	private int age;
	private List<String> habby;
	

	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> getHabby() {
		return habby;
	}
	public void setHabby(List<String> habby) {
		this.habby = habby;
	}
	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.habby);
	}
	
	

接下来我们配置文件(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 class="com.thf.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
   <bean class="com.thf.ioc.web.UserAcion" id="xxx">
   <!--set注入用property标签 -->
   <property name="userBiz" ref="userBiz"></property>
    <property name="uname" value="thf"></property>
      <property name="age" value="18"></property> 
   <property name="habby">
   <list>
   <value>打篮球</value>
   <value>听歌</value>
   <value>敲代码</value>
   </list>
   </property>
   </bean>
   <bean class="com.thf.ioc.web.OrderAcion" id="ttt">
   <property name="userBiz" ref="userBiz"></property>
   </bean>
  
</beans>

测试

package com.thf.ioc.test;

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

import com.thf.ioc.web.OrderAcion;
import com.thf.ioc.web.UserAcion;

public class IocTest {

	public static void main(String[] args) {
//		UserAcion userAcion=new UserAcion();
//		userAcion.upload();
	
		//建模
		ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
	   UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
	  // OrderAcion orderAcion = (OrderAcion) springContext.getBean("ttt");
	   // userAcion.upload();
      //  orderAcion.upload();
	    userAcion.test1();
	   
	}
}

结果:
在这里插入图片描述
2、构造注入
构造注入就是在实体类中一样,把set,get注释 ,然后为属性写上构造方法,也就是直接创建一个构造方法

package com.thf.ioc.web;

import java.util.List;

import com.thf.ioc.biz.UserBiz;
import com.thf.ioc.biz.impl.UserBizImpl;
import com.thf.ioc.biz.impl.UserBizImpl2;
/**
 * ioc的注入方式及各类类型   有三种注入方式:
 * 
 * set注入
 * 基本类型与String
 * 数组
 * 自定义类型
 * 
 * 构造注入
 * 自动装配
 * spring4之后出现的
 * byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
 * byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
 * 
 * @author Administrator
 *
 */
public class UserAcion {
      
	private UserBiz userBiz;//自定义类型
	private String uname;
	private int age;
	private List<String> habby,
	
public UserAcion(String uname, int age) {
		super();
		this.uname = uname;
		this.age = age;
	}

public UserAcion() {
	super();
}

//	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> getHabby() {
		return habby;
	}
	public void setHabby(List<String> habby) {
		this.habby = habby;
	}
	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.habby);
	}
	
	
}

然后在去spring-context.xml配置
构造注入用 <constructor-arg>标签

<?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 class="com.thf.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
   <bean class="com.thf.ioc.web.UserAcion" id="xxx">
   <!--set注入用property标签 -->
   <property name="userBiz" ref="userBiz"></property>
    <!-- <property name="uname" value="thf"></property> -->
     <!--  <property name="age" value="18"></property>  -->
     
   <!-- 构造注入用 <constructor-arg>标签 -->
   <constructor-arg name="uname" value="thf1"></constructor-arg>
   <constructor-arg name="age" value="18"></constructor-arg>
   <property name="habby">
   <list>
   <value>打篮球</value>
   <value>听歌</value>
   <value>敲代码</value>
   </list>
   </property>
   </bean>
   
   
   <bean class="com.thf.ioc.web.OrderAcion" id="ttt">
   <property name="userBiz" ref="userBiz"></property>
   </bean>
  
</beans>

测试

package com.thf.ioc.test;

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

import com.thf.ioc.web.OrderAcion;
import com.thf.ioc.web.UserAcion;

public class IocTest {

	public static void main(String[] args) {
//		UserAcion userAcion=new UserAcion();
//		userAcion.upload();
		
		
		//建模
		ApplicationContext springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
	    UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
	    //OrderAcion orderAcion = (OrderAcion) springContext.getBean("ttt");
	  //  userAcion.upload();
        //orderAcion.upload();
	    userAcion.test1();
	   
	}
}

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

3、自动装配
我们在spring-context.xml加了一个default-autowire=“byType”
自动装配是在spring4之后出现的
byType:根据配置的Bean中的接口,在spring的上下文寻找对应的实现类
byName:根据配置的Bean中的接口名字,在spring的上下文寻找对应的实现类
在这里插入图片描述
4、spring的上下文交给tomcat上下文管理
spring 作为管理整个工程中所有的javabean,
那么如何在用户发送请求的时候能够访问到指定的javabean呢?
处理方式是:
监听器中将spring的上下文交给tomcat的上下文中进行管理
思路: 浏览器—>request---->servlertContext---->springContext—>任意的javabean

接下来我们要建一个SpringLoaderListener类实现ServletContextListener
在运行tomcat的时候就会执行这个类 主要是因为加了@WebListener

package com.thf.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呢?
 * 处理方式是:
 *       监听器中将spring的上下文交给tomcat的上下文中进行管理
 * 思路: 浏览器--->request---->servlertContext---->springContext--->任意的javabean
 * 
 * @author Administrator
 *
 */
@WebListener
public class SpringLoaderListener implements ServletContextListener {
	

	@Override
	public void contextInitialized(ServletContextEvent sce) {
	  System.out.println("tomcat一启动就触发了。。。");
	  ServletContext tomcatContext= sce.getServletContext(); //拿tomcat的上下文中
	  String springXmlLocation=tomcatContext.getInitParameter("springXmlLocation");
	  System.out.println("spring的上下文配置文件:"+springXmlLocation);///查看web.xml中查看是否配置
	  ApplicationContext springContext=null;
	  if(springXmlLocation ==null && "".equals(springXmlLocation)) {
		 springContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		  
	  }else {
		  springContext=new ClassPathXmlApplicationContext(springXmlLocation);
	  }
	  
	  //作用域
	  tomcatContext.setAttribute("spring_key", springContext);//将建模后的文件以键值对的形式放入
	  
	  
	}

	
}

然后配置我们写的springXmlLocation

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

接下来我们要写一个UserServlet
在上面就已经将springContext加入到了servletContext中
所以就可以直接获取到springContext的键值对。
然后我们在这个类中执行一下

package com.thf.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 {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("处理用户请求");
		//通过req.getServletContext()拿到tomcat上下文 然后通过.getAttribute("spring_key");拿到spring的上下文
		 ApplicationContext springContext=(ApplicationContext) req.getServletContext().getAttribute("spring_key");
		 UserAcion userAcion = (UserAcion) springContext.getBean("xxx");
	     userAcion.upload();
	}
}

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值