首頁 > 軟體

Spring框架之IOC介紹講解

2022-08-25 14:00:56

一、對spring的理解

spring是一個開源框架,它由Rod Johnson 建立。它是為了解決企業應用開發的複雜性而建立的。

目的:解決企業應用開發的複雜性

功能:使用基本的JavaBean代替EJB,並提供了更多的企業應用功能

範圍:任何Java應用

簡單來說,Spring是一個輕量級的控制反轉(IoC)和麵向切面(AOP)的容器框架。

二、spring中ioc的特點

建一個maven專案

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.yzp</groupId>
  <artifactId>T280_spring</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>T280_spring Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--  將當前專案所用的jar包依賴版本定義在外部目的在於所有jar
 		 包版本進行統一管理-->
  <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>T280_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>

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>
</web-app>

2.1控制反轉

建一個com.yzp.biz的包

UserBiz

package com.yzp.biz;
/**
 * 使用者業務類
 * @author yzp
 *
 */
public interface UserBiz {
	void list();
}

建一個com.yzp.biz.impl的包

UserBizImpl1

package com.yzp.biz.impl;
import com.yzp.biz.UserBiz;
public class UserBizImpl1 implements UserBiz{
	@Override
	public void list() {
		System.out.println("查詢使用者資料。。按照年齡排序。");
	}
}

UserBizImpl2

package com.yzp.biz.impl;
import com.yzp.biz.UserBiz;
public class UserBizImpl2 implements UserBiz{
	@Override
	public void list() {
		System.out.println("查詢使用者資料。。按照入職時間排序。");
	}
}

建一個com.yzp.web的包

OrderAction

package com.yzp.web;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
public class OrderAction {
private UserBiz userBiz = new UserBizImpl1();
	public void list() {
		userBiz.list();
	}
}

UserAction

package com.yzp.web;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
public class UserAction {
	private UserBiz userBiz = new UserBizImpl1();
	public void list() {
		userBiz.list();
	}
}

常規做法即運用spring之前的處理方法

需求:
同時在使用者模組,訂單模組拿到所有的使用者資料
需求變更1:
同時在使用者模組,訂單模組拿到所有的使用者資料,並且要求使用者資料是通過年齡排序的
對應策略:修改UserBiz中list方法,新增排序功能
需求變更2:
同時在使用者模組,訂單模組拿到所有的使用者資料,並且要求使用者資料是通過註冊時間排序的
對應策略,修改UserBiz中list方法,新增排序功能,按照時間點排序

總結:
最原始:頻繁修改業務層biz的程式碼
多實現:凡是涉及到使用者業務層呼叫的地方,都需要修改程式碼

將spring的組態檔加入

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>

注意:一定要在有網路的情況下進行,否則約束不生效

IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理

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

	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<!-- <bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz1"></bean> -->
	<bean class="com.yzp.biz.impl.UserBizImpl2" id="userBiz2"></bean>
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
	<bean class="com.yzp.web.OrderAction" id="orderAction"></bean>
</beans>

UserAction

package com.yzp.web;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
public class UserAction {
	//private UserBiz userBiz = new UserBizImpl1();
	private UserBiz userBiz;
	public void list() {
		userBiz.list();
	}
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
}

建一個com.yzp.ioc的包

在裡面建一個Demo1的類

建模,列印com.yzp.biz.impl.UserBizImpl2中的語句

package com.yzp.ioc;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yzp.web.UserAction;
public class Demo1 {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//建模
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
	}
}

執行結果:

可見 能拿到

 總結

1.對spring框架的組態檔進行建模,建模之後spring-context.xml中所有的Javabean資訊
 都會載入進spring容器的上下文中
2.上下文中就包含了spring-context.xml 所有物件

測試orderaction也拿到相同結果,設定和orderaction都如useraction一致修改

package com.yzp.web;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
public class OrderAction {
//private UserBiz userBiz = new UserBizImpl1();
	private UserBiz userBiz;
	public void list() {
		userBiz.list();
	}
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
}
<?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">
	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<!-- <bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz1"></bean> -->
	<bean class="com.yzp.biz.impl.UserBizImpl2" id="userBiz2"></bean>
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
	<bean class="com.yzp.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
</beans>
package com.yzp.ioc;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yzp.web.OrderAction;
import com.yzp.web.UserAction;
/**
 * 1.對spring框架的組態檔進行建模,建模之後spring-context.xml中所有的Javabean資訊
 * 都會載入進spring容器的上下文中
 * 2.上下文中就包含了spring-context.xml 所有物件
 * @author yzp
 *
 */
public class Demo1 {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//建模
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
		OrderAction orderAction = (OrderAction) context.getBean("orderAction");
		orderAction.list();
	}
}

結果:

若是要按年齡排序,就只需要修改組態檔就OK了

<?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">
	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz2"></bean>
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
	<bean class="com.yzp.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
</beans>

2.2注入依賴

方式① set注入

UserAction

package com.yzp.web;
import java.util.List;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
public class UserAction {
	//private UserBiz userBiz = new UserBizImpl1();
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	private String name;
	private int age;
	private List<String> hobby;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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 void list() {
		System.out.println(name);
		System.out.println(age);
		System.out.println(hobby);
		userBiz.list();
	}
}
<?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">
	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz2"></bean>
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz2"></property>
		<!--set注入  -->
		<property name="age" value="22"></property>
		<property name="name" value="cdl"></property>
		<property name="hobby">
			<list>
				<value>籃球</value>
				<value>足球</value>
				<value>唱歌</value>
			</list>
		</property>
	</bean>
	<bean class="com.yzp.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz2"></property>
	</bean>
</beans>
package com.yzp.ioc;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yzp.web.OrderAction;
import com.yzp.web.UserAction;
/**
 * 1.對spring框架的組態檔進行建模,建模之後spring-context.xml中所有的Javabean資訊
 * 都會載入進spring容器的上下文中
 * 2.上下文中就包含了spring-context.xml 所有物件
 * @author yzp
 * 
 * IOC特點(控制反轉):將建立物件的權利反轉給spring容器來完成
 * 
 *
 */
public class Demo1 {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		//建模
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
		OrderAction orderAction = (OrderAction) context.getBean("orderAction");
		orderAction.list();
	}
}

結果;

方式② 構造注入

OrderAction

package com.yzp.web;
import java.util.List;
import com.yzp.biz.UserBiz;
import com.yzp.biz.impl.UserBizImpl1;
/**
 * 依賴注入的三種方式:
 * 1.set注入
 * 2.構造注入
 * 3.自動裝配
 *  byName
 *  byType
 * @author yzp
 *
 */
public class OrderAction {
//private UserBiz userBiz = new UserBizImpl1();
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	private String name;
	private int age;
	private List<String> hobby;
	public OrderAction(String name, int age, List<String> hobby) {
		super();
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}
	public OrderAction() {
		super();
		// TODO Auto-generated constructor stub
	}
	public void list() {
		System.out.println(name);
		System.out.println(age);
		System.out.println(hobby);
		userBiz.list();
	}
}
<?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">
	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz2"></bean>
	<!--set注入  -->
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz2"></property>
		<property name="age" value="22"></property>
		<property name="name" value="cdl"></property>
		<property name="hobby">
			<list>
				<value>籃球</value>
				<value>足球</value>
				<value>唱歌</value>
			</list>
		</property>
	</bean>
	<!-- 構造注入 -->
	<bean class="com.yzp.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz2"></property>
		<constructor-arg name="name" value="yzp"></constructor-arg>
		<constructor-arg name="age" value="23"></constructor-arg>
		<constructor-arg name="hobby">
				<list>
				<value>籃球1</value>
				<value>足球1</value>
				<value>唱歌1</value>
				</list>
		</constructor-arg>
	</bean>
</beans>

執行結果:

方式③ 自動裝配

將set和構造的注入 註釋

byType不報錯 byName報錯

自動裝配
 default-autowire="byName" 
 byName:是通過spring管理的bean物件的ID進行查詢,如果找不到,則注入失敗,反之成功
 byType:是通過spring管理的bean物件的介面實現類進行查詢,如果沒有或者2個以上,則注入失敗,反之成功

三、spring與web容器的整合

分析:

spring與web容器的整合原理
    why:建模的過程是十分耗時的
  解決問題:
 1.建模必不可少
 2.建模只保障只執行一次
 3.建模後期望在每一個servlet都能夠拿到spring的上下文物件ClassPathXmlApplicationContext
   how:
  1.監聽器的初始化方法 只執行一次
  2.spring的上下文要存放在Tomcat上下文中

建一個包com.yzp.ioc.listener

package com.yzp.ioc.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringLoadListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("初始化執行");
		ServletContext servletContext = sce.getServletContext();
		String springConfigLocation = servletContext.getInitParameter("springConfigLocation");
		System.out.println(springConfigLocation+"...");
		//拿到spring上下文
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		//將spring的上下文儲存在Tomcat上下文中
		servletContext.setAttribute("springContext", context);
	}
}

在com.yzp.ioc中建一個類DemoServlet

package com.yzp.ioc;
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.support.ClassPathXmlApplicationContext;
import com.yzp.web.UserAction;
/**
 * spring與web容器的整合原理
 * 	why:建模的過程是十分耗時的
 * 解決問題:
 * 1.建模必不可少
 * 2.建模只保障只執行一次
 * 3.建模後期望在每一個servlet都能夠拿到spring的上下文物件ClassPathXmlApplicationContext
 * how:
 * 1.監聽器的初始化方法 只執行一次
 * 2.spring的上下文要存放在Tomcat上下文中
 * @author yzp
 * 
 */
@WebServlet("/springDemo")
public class DemoServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1){
		//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
		ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) arg0.getServletContext().getAttribute("springContext");
		UserAction userAction = (UserAction) context.getBean("userAction");
		userAction.list();
	}
}

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">
	<!-- IOC的主要作用管理整個專案的Javabean:依靠依賴注入、控制反轉的特點進行管理 -->
	<bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz"></bean>
	<bean class="com.yzp.biz.impl.UserBizImpl1" id="userBiz1"></bean>
	<!--set注入  -->
	<bean class="com.yzp.web.UserAction" id="userAction">
		<property name="userBiz" ref="userBiz1"></property> 
		<property name="age" value="22"></property>
		<property name="name" value="cdl"></property>
		<property name="hobby">
			<list>
				<value>籃球</value>
				<value>足球</value>
				<value>唱歌</value>
			</list>
		</property>
	</bean>
	<!-- 構造注入 -->
	<bean class="com.yzp.web.OrderAction" id="orderAction">
		<property name="userBiz" ref="userBiz1"></property> 
		<constructor-arg name="name" value="yzp"></constructor-arg>
		<constructor-arg name="age" value="23"></constructor-arg>
		<constructor-arg name="hobby">
				<list>
				<value>籃球1</value>
				<value>足球1</value>
				<value>唱歌1</value>
				</list>
		</constructor-arg>
	</bean>
	<!-- 自動裝配 -->
</beans>

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>springConfigLocation</param-name>
		<param-value>/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>com.yzp.ioc.listener.SpringLoadListener</listener-class>
	</listener>
</web-app>

到此這篇關於Spring框架之IOC介紹講解的文章就介紹到這了,更多相關Spring IOC內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com