Spring之IOC(带详细案例操作)

Spring之IOC

1.Spring是什么以及作用?

Spring是主要作用体现在:控制反转(IOC)、面向切面(AOP)的容器框架和整合框架的粘合剂,今天我主要解释它的控制反转(IOC)

 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处理。
应用场景:
当需求变化非常快的时候,不便于维护,因为维护的权利是属于程序员的,spring的ioc角色解决这一问题的,将维护代码的权力由程序员转教给spring容器来完成。**

Spring 管理Bean(java文件)的注入方式

Spring文件的配置名详情

   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

写一个set注入

需要导的依赖jar包

<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.lix</groupId>
  <artifactId>lix_Spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>lix_Spring 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>lix_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>

UserAction实体类

package lix.ioc.biz.web;

import java.util.List;

import lix.ioc.biz.UserBiz;


/**
 * IOC的注入方式以及各类型
 * set注入
 * 		基本类型与String
 * 		数组
 *  	自定义类型
 * 构造注入
 * 自动装配
 * @author 20190816
 *
 */
public class UserAction {
	private UserBiz userBiz;
	private String uname;
	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;
	}


	private int age;
	private List<String> hobby;
	

	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	
	
	public void upload() {
		userBiz.upload();
	}
	/**
	 * set 注入问题
	 */
	public void test01() {
		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:aop="http://www.springframework.org/schema/aop"
	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/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
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">

	<bean class="lix.ioc.biz.imp.UserBizImp01" id="userBiz"></bean>

	<bean class="lix.ioc.biz.web.UserAction" id="ua">
		<property name="userBiz" ref="userBiz"></property>
		<property name="uname" value="zhangsan"></property>
		<property name="age" value="18"></property>
		<property name="hobby">
			<list>
				<value>唱歌</value>
				<value>跳舞</value>
				<value>篮球</value>
			</list>
		</property>

	</bean>

	<bean class="lix.ioc.biz.web.OrderAction" id="oa">
		<property name="userBiz" ref="userBiz"></property>
	</bean>

</beans>

测试IOCTest

package lix.ioc.biz.test;

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

import lix.ioc.biz.web.OrderAction;
import lix.ioc.biz.web.UserAction;

public class IocTest {
	public static void main(String[] args) {
//		UserAction userAction=new UserAction();
//		userAction.upload();
		
		ApplicationContext springcontext= new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction useraction=(UserAction) springcontext.getBean("ua");
//		OrderAction orderaction=(OrderAction) springcontext.getBean("oa");
//		useraction.upload();
//		orderaction.upload();
		useraction.test01();//调用方法
		
	}
}

执行结果
在这里插入图片描述

** UserBizImp02**

package lix.ioc.biz.imp;

import lix.ioc.biz.UserBiz;

public class UserBizImp02 implements UserBiz{
	public  void upload() {
		System.out.println("实现用户上传功能");
		System.out.println("实现客户优化功能");
	}
}


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"
	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/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
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">

	<bean class="lix.ioc.biz.imp.UserBizImp02" id="userBiz"></bean>

	<bean class="lix.ioc.biz.web.UserAction" id="ua">
		<!-- set注入property标签 -->
		<!-- <property name="userBiz" ref="userBiz"></property> -->
		<!-- <property name="uname" value="zhangsan"></property> -->
		<!-- <property name="age" value="18"></property> -->
		<!-- set注入property标签 -->
		<constructor-arg name="uname" value="小吴"></constructor-arg>
		<constructor-arg name="age" value="19"></constructor-arg>
		<property name="hobby">
			<list>
				<value>唱歌</value>
				<value>跳舞</value>
				<value>篮球</value>
			</list>
		</property>

	</bean>

	<bean class="lix.ioc.biz.web.OrderAction" id="oa">
		<!-- <property name="userBiz" ref="userBiz"></property> -->
	</bean>

</beans>

测试IOCTest



package lix.ioc.biz.test;

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

import lix.ioc.biz.web.OrderAction;
import lix.ioc.biz.web.UserAction;

public class IocTest {
	public static void main(String[] args) {
//		UserAction userAction=new UserAction();
//		userAction.upload();
		
		ApplicationContext springcontext= new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction useraction=(UserAction) springcontext.getBean("ua");
		OrderAction orderaction=(OrderAction) springcontext.getBean("oa");
		useraction.upload();
		orderaction.upload();
//		useraction.test01();
		
	}
}

执行结果
在这里插入图片描述

Spring与Web项目的集成

WEB项目如何读取spring上下文
通过监听器实现ServletContextListener
contextConfigLocation:classpath:applicationContext-*.xml

  • spring.pom
    spring-context
    spring-orm
    spring-web
    spring-aspects
    注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持

  • 简介
    spring-context.xml
    ioc
    set注入
    基本数据类型注入
    集合注入
    对象注入
    构造注入
    基本数据类型注入
    自动装配

  • tomcat整合ioc容器


需要导入的依赖包pomxml
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.10.RELEASE</version>
</dependency>

创建一个SpringloaderListener类(监听器类)

package lix.ioc.biz.lisener;

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  z作为管理整个工程中的所有的javabean,那么如何在用户发送请求的时候能够访问导JavaBean
 * @author 20190816
 * 处理方式:
 * 		在监听器中将spring的上下文交给tomcat的上下文进行管理
 * 		浏览器--》request--》servletContext--》SpringContext--》任意JavaBean
 *
 */
@WebListener
public class SpringLoaderListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("tomcat一启动就触发了");
		ServletContext tomcatContext=sce.getServletContext();
		String springXmlLocation=tomcatContext.getInitParameter("springXmlLocation");
		System.out.println("spring的上下文配置文件:"+springXmlLocation);
		ApplicationContext springContext=null;
		if(springXmlLocation==null || "".equals(springXmlLocation)) {
			springContext=(ApplicationContext) new ClassPathXmlApplicationContext().getBean("/spring-context.xml");
		}else {
			springContext=(ApplicationContext) new ClassPathXmlApplicationContext(springXmlLocation);
		}
		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>

创建一个userServlet

package lix.ioc.biz.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("ua");
		useraction.upload();
	}
}

注意!!!!这里需要在创建一个spring-other.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"
	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/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
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd">

	<bean class="lix.ioc.biz.imp.UserBizImp02" id="userBiz"></bean>

	<bean class="lix.ioc.biz.web.UserAction" id="ua">
		<!-- set注入property标签 -->
		<!-- <property name="userBiz" ref="userBiz"></property> -->
		<!-- <property name="uname" value="zhangsan"></property> -->
		<!-- <property name="age" value="18"></property> -->
		<!-- set注入property标签 -->
		<constructor-arg name="uname" value="小吴"></constructor-arg>
		<constructor-arg name="age" value="19"></constructor-arg>
		<property name="hobby">
			<list>
				<value>唱歌</value>
				<value>跳舞</value>
				<value>篮球</value>
			</list>
		</property>

	</bean>

	<bean class="lix.ioc.biz.web.OrderAction" id="oa">
		<!-- <property name="userBiz" ref="userBiz"></property> -->
	</bean>

</beans>

执行Userservlet的结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值