Spring之IOC
Posted xhpcc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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处理
3. 如何在spring当中定义和配置一个JavaBean
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
代码:
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.xhp</groupId> <artifactId>Spring</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </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>
spring-context.xml配置,一种安装spring的插件 也就是本地安装,一种在线安装就是直接复制下面的代码,到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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
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" default-autowire="byName" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <bean class="com.xhp.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean> <bean class="com.xhp.ioc.web.UserAction" id="xxx"> <!--set注入用property标签 --> <!-- <property name="userBiz" ref="userBiz"></property> --> <!-- <property name="uname" value="zs"></property> <property name="age" value="22"></property> --> <!--set注入用constructor-arg标签 --> <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.xhp.ioc.web.OrderAction" id="ttt"> <property name="userBiz" ref="userBiz"></property> </bean> </beans>
写一个UserBiz.java接口
再用一个类去实现它的方法、
package com.xhp.ioc.biz.impl; import com.xhp.ioc.biz.UserBiz; public class UserBizImpl1 implements UserBiz @Override public void upload() System.out.println("开始优化性能的代码"); System.out.println("实现用户上传");
在写web层
UserAction.java:
package com.xhp.ioc.web; import java.util.List; import com.xhp.ioc.biz.UserBiz; /** * IOC的注入方式及各类类型 * set注入 * 基本类型与String * 数组 * 自定义类型 * 构造注入 * 自动装配 * * 构造注入 * 自动装配 * spring4之后出现的 * byType:根据配置的Bean中的接口,在Spring的上下文中寻找对应的实现类 * byName:根据配置的Bean中的接口名字,在Spring的上下文中寻找对应的实现类 * @author xhp * */ public class UserAction private UserBiz userBiz; private String uname; private int age; private List<String> hobby; public UserAction() super(); // TODO Auto-generated constructor stub public UserAction(String uname, int age) super(); this.uname = uname; this.age = age; public UserBiz getUserBiz() return userBiz; public void setUserBiz(UserBiz userBiz) this.userBiz = userBiz; public List<String> getHobby() return hobby; public void setHobby(List<String> hobby) this.hobby = hobby; public void upload() userBiz.upload(); /** * 注入问题 */ public void test1() System.out.println(this.uname); System.out.println(this.age); System.out.println(this.hobby);
测试类IocTest.java
package com.xhp.ioc.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.xhp.ioc.web.OrderAction; import com.xhp.ioc.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("xxx"); OrderAction orderAction=(OrderAction) springContext.getBean("ttt"); userAction.upload(); orderAction.upload(); // userAction.test1();
创建一个监听器 SpringLoaderListenter
package com.xhp.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,那么如何在用户发送请求的时候能够访问到 * 处理方式: * 在监听器中将spring的上下文交给tomcat的上下文中进行管理 * 浏览器--》request-->servletContext-->springContext-->任意的javaBean * @author xhp * */ @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 = new ClassPathXmlApplicationContext("/spring-context.xml"); else springContext = new ClassPathXmlApplicationContext(springXmlLocation); tomcatContext.setAttribute("spring_key", springContext);
创建servlet UserServlet
package com.xhp.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();
在配置xml就OK了
以上是关于Spring之IOC的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot脚手架项目002-004.Spring IOC_权限管理系统_Spring:什么是IOCSpring Bean注入SpringBean的注解bean的加载流程
Springday02 jabcTemplate注解IOC创建对象注解IOC注入注解 IO生命周期纯注解IOCSpring-junitAOP-JDK和CGLIB动态代理
JAVAWEB开发之Spring详解之——Spring的入门以及IOC容器装配Bean(xml和注解的方式)Spring整合web开发整合Junit4测试