Spring之IOC

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

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

** 1.2 容器框架**

 JavaBean	项目中的一个个类
     IOC和AOP

2. 什么是控制反转(或依赖注入)

控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
案例:实现Spring的IoC

IOC/DI
将以前由程序员实例化对象/赋值的工作交给了spring处理

3. 如何在spring当中定义和配置一个JavaBean(使用无参构造方法+set方法创建一个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

注1:struts2的Action请使用多例模式

4. 简单属性的配置:

8+1+3
8基础数据+String+3个sql
java.util.Date
java.sql.Date
java.sql.Time
java.sql.Timestamp
通过标签赋值即可

5. 复杂属性的配置

5.1 JavaBean
ref bean=""
5.2 List或数组
5.3 Map
5.4 Properties

6. 针对项目,配置文件路径的2种写法

ApplicationContext
String path = “applicationContext.xml”;
String path = “classpath:applicationContext-*.xml”;//src
String[] path = new String[] { “applicationContext-a.xml”, “applicationContext-b.xml” };//分模块开发

7.案例

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.zking</groupId>
	<artifactId>T226_spring</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>T226_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>T226_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>

set注入和构造注入

实体类
UserAction

package com.likang.ioc.web;

import java.util.List;

import com.likang.ioc.biz.UserBiz;
import com.likang.ioc.biz.impl.UserBizImpl1;
import com.likang.ioc.biz.impl.UserBizImpl2;

/**
 * IOC的注入方式及各类类型
 * 	 	set注入
 * 			基本类型与string
 * 			数组
 * 			自定义类型
 * 
 * 		构造注入
 * 		自动装配
 * 			spring4之后出现的
 * 			byType:根据配置的bean中的接口,在spring的上下文中寻找对应的实现类
 * 			byName:根据配置的bean中的接口名字,在spring的上下文中寻找对应的实现类
 * @author Hasee
 *
 */
public class UserAction {

	private UserBiz userBiz;
	private String uname;
	private int age;
	private List<String> hobby;
	
	
public UserAction(String uname, int age) {
		super();
		this.uname = uname;
		this.age = age;
	}



public UserAction() {
	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> 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;
	}



	public void upload() {
		userBiz.upload();
	}
	
	
	/**
	 * 注入问题
	 */
	public void test1() {
		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:context="http://www.springframework.org/schema/context"
	default-autowire="byType"
	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.likang.ioc.biz.impl.UserBizImpl1" id="userBiz"></bean>
	 <bean class="com.likang.ioc.web.UserAction" id="xxx"> 
		<!-- set注入用property标签 -->
		<!-- <property name="userBiz" ref="userBiz"></property> -->
		<!-- <property name="uname" value="康"></property> <property name="age" 
			value="19"></property> -->
		<!-- 构造注入用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="com.likang.ioc.web.OrderAction" id="ttt">
		<!-- <property name="userBiz" ref="userBiz"></property> -->
	</bean>
</beans>

两个不同的class来测试

package com.likang.ioc.biz.impl;

import com.likang.ioc.biz.UserBiz;

public class UserBizImpl1 implements UserBiz{

	@Override
	public void upload() {
		// TODO Auto-generated method stub
		System.out.println("实现用户上传的功能");
	}

}

package com.likang.ioc.biz.impl;

import com.likang.ioc.biz.UserBiz;

public class UserBizImpl2 implements UserBiz{

	@Override
	public void upload() {
		// TODO Auto-generated method stub
		System.out.println("开始优化性能的代码");
		System.out.println("实现用户上传的功能");
	}

}

实现类

package com.likang.ioc.test;

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

import com.likang.ioc.web.OrderAction;
import com.likang.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();
	}
}

在这里插入图片描述

自动装配
byName 是根据你配置的id还找到类;

byType 通过类型来配置,只会找到接口等,如果有两个类实现了同一个接口,那么就容易报错

	default-autowire="byType"
	default-autowire="byName"

spring与tomcat的运用

SpringloderListener

package com.likang.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--》servletcontext--》spring context --》任意的JavaBean
 * @author Hasee
 *
 */
@WebListener
public class SpringLoaderListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("tomcat一启动就触发了.....");
		ServletContext tomcatContext = sce.getServletContext();
		String springXml=tomcatContext.getInitParameter("springXml");
		ApplicationContext springContext=null;
		if(springXml==null || "".equals(springXml)) {
			 springContext= new ClassPathXmlApplicationContext("/spring-context.xml");
			System.out.println("sssss");
		}else {
			 springContext= new ClassPathXmlApplicationContext(springXml);

		}
		
		System.out.println("spring的上下文配置文件:"+springXml);
		System.out.println();
		tomcatContext.setAttribute("spring_key",springContext);
	}
		
	

}

web.xml 配置

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
 id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Application</display-name>
  
  <context-param>
  	<param-name>springXmlLocation</param-name>
  	<param-value>/spring-other.xml</param-value>
  </context-param>
  
  <context-param>
  	<param-name>springXml</param-name>
  	<param-value>/spring-other.xml</param-value>
  </context-param>
 
</web-app>

UserServlet

package com.likang.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{

/**
	 * 
	 */
	private static final long serialVersionUID = -5952264846320465780L;

@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 {
		// TODO Auto-generated method stub
System.out.println("处理用户请求");
ApplicationContext springContext = (ApplicationContext)req.getServletContext().getAttribute("spring_key");
UserAction userAction= (UserAction)springContext.getBean("xxx");
userAction.upload();
}
}

结果如下

八月 14, 2019 1:46:21 上午 org.apache.tomcat.util.digester.SetPropertiesRule begin
警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:T226_spring' did not find a matching property.
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server version:        Apache Tomcat/8.0.47
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server built:          Sep 29 2017 13:46:41 UTC
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server number:         8.0.47.0
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Name:               Windows 10
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Version:            10.0
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Architecture:          amd64
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Java Home:             C:\Program Files\Java\jdk1.8.0_144\jre
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Version:           1.8.0_144-b01
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM Vendor:            Oracle Corporation
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_BASE:         D:\2t226\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_HOME:         D:\y2\apache-tomcat-8.0.47\apache-tomcat-8.0.47
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.base=D:\2t226\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.home=D:\y2\apache-tomcat-8.0.47\apache-tomcat-8.0.47
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dwtp.deploy=D:\2t226\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Djava.endorsed.dirs=D:\y2\apache-tomcat-8.0.47\apache-tomcat-8.0.47\endorsed
八月 14, 2019 1:46:21 上午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dfile.encoding=UTF-8
八月 14, 2019 1:46:21 上午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_144\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_152/bin/server;C:/Program Files/Java/jre1.8.0_152/bin;C:/Program Files/Java/jre1.8.0_152/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;D:\Program Files (x86)\MySQL\MySQL Server 5.5\bin;D:\y2\10、Maven(1)\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0\bin;D:\y2\10、Maven(1)\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0\bin;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Hasee\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;"D:\y2\10、Maven(1)\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0\bin;D:\y2\10、Maven(1)\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\apache-maven-3.5.0\bin;";;D:\y2\eclipse-jee-oxygen-1a-win32-x86_64\eclipse;;.
八月 14, 2019 1:46:22 上午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
八月 14, 2019 1:46:22 上午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
八月 14, 2019 1:46:22 上午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-nio-8009"]
八月 14, 2019 1:46:22 上午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
八月 14, 2019 1:46:22 上午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1006 ms
八月 14, 2019 1:46:22 上午 org.apache.catalina.core.StandardService startInternal
信息: Starting service Catalina
八月 14, 2019 1:46:22 上午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.0.47
八月 14, 2019 1:46:25 上午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
八月 14, 2019 1:46:27 上午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
tomcat一启动就触发了.....
八月 14, 2019 1:46:28 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@51e5beec: startup date [Wed Aug 14 01:46:28 CST 2019]; root of context hierarchy
八月 14, 2019 1:46:28 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-other.xml]
spring的上下文配置文件:/spring-other.xml

八月 14, 2019 1:46:29 上午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
八月 14, 2019 1:46:29 上午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]
八月 14, 2019 1:46:29 上午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-nio-8009"]
八月 14, 2019 1:46:29 上午 org.apache.catalina.startup.Catalina start
信息: Server startup in 6996 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值