Spring之ioc

Spring 在 学术界 有Spring全家桶之称(在各个领域都有涉及)

Spring全家桶    架构方案层面
spring struts Hibernate
spring springmvc mybatis
springboot    dubbox(16年到19年与Spring分庭抗议)
SpringCloud

技术层面
安全技术方面:Shiro        springSecurity
数据库层面:hibernate/mybatis    SpringDataJpa
消息中间件:activityMQ、RabbitMQ、kaffka    spring..MQ
 还有很多我就不一一列举

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

Spring是一个开源框架,为了(目的)解决企业应用开发的复杂性而创建的。

 功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能

 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.1 两大特点

①、中间层框架、万能胶

②、容器框架

框架与框架之间需要整合

 

 spring包含的核心模块

 

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

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


3. 如何在spring当中定义和配置一个JavaBean(使用无参构造方法+set方法创建一个JavaBean)
   ① id:在容器中查找Bean的id(唯一、且不能以/开头)
   ② class:bean的完整类名
   ③ name:在容器中查找Bean的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
   ④ scope:(singleton|prototype)默认是singleton
      ④.1 singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
      ④.2 prototype(原型模式/多例模式):一个bean定义对应多个对象实例
   ④ abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
   ⑤ parent:指定一个父bean(必须要有继承关系才行)
   ⑥ init-method:指定bean的初始化方法
   ⑦ 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
   通过<value>标签赋值即可

5. 复杂属性的配置
  ① JavaBean: ref bean=""  ② List或数组  ③ Map  ④ 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. spring与web项目的集成

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

8. log4j2

9. spring.pom、spring-context、 spring-orm、spring-web、spring-aspects

   注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持

 一、IOC

1、什么是IOC

做一个上传的功能,普通写法和spring写法的区别

使用的相关类:

package com.lj.ioc.biz;
/**
 * 接口
 *
 */
public interface UserBiz {
	public void upload();
}

(1)普通写法

①、第一个版本(原始版本)

package com.lj.ioc.biz.impl;
import com.lj.ioc.biz.UserBiz;
/**
 * 需求:做一个上传的功能
 * 功能:上传功能
 * 提出整改:
 * 1、限定上传文件大小   2、限定上传文件类别
 * 总结:
 * 1、更新版本需要改动原有代码
 * 2、相关调用此方法的模块伴随巨大的风险
 *
 *action1   需要加限制
 *action2   不需要加限制
 */
public class UserBizImpl1 implements UserBiz{
	
	public void upload() {
//      做整改报错撤回去的代码
//		System.out.println("做条件判断限定,文件太大不能上传");
		System.out.println("循规蹈矩的把功能开发出来");
		
	}
}

 第二个版本(更新后版本)

package com.lj.ioc.biz.impl;
import com.lj.ioc.biz.UserBiz;
public class UserBizImpl2 implements UserBiz{
	public void upload() {
		System.out.println("做条件判断限定,文件太大不能上传");
		System.out.println("循规蹈矩的把功能开发出来");
		
	}
}

 ②、假设有两个模块要使用(一个本模块,一个关联模块)

UserAction :

package com.lj.ioc.web;
/**
 *这个使用第一个版本
 */
import com.lj.ioc.biz.UserBiz;
import com.lj.ioc.biz.impl.UserBizImpl1;
public class UserAction {
	private UserBiz userBiz=new UserBizImpl1();
	public void upload() {
		userBiz.upload();
	}
 
	public static void main(String[] args) {
		UserAction userAction=new UserAction();
		userAction.upload();
		
	}	
}

结果: 

PersonAction : 

package com.lj.ioc.web;
/**
 *这个使用第二个版本
 */
import com.lj.ioc.biz.UserBiz;
import com.lj.ioc.biz.impl.UserBizImpl1;
import com.lj.ioc.biz.impl.UserBizImpl2;
public class PersonAction {
	private UserBiz userBiz=new UserBizImpl2();
	public void upload() {
		userBiz.upload();
	}
	
	public static void main(String[] args) {
		PersonAction personAction=new PersonAction();
		personAction.upload();	
	}
}

 结果:

 弊端:

 如果有100个需要整改模块,那就需要改100次原有代码(繁琐);

同时,相关调用此方法的模块伴随巨大的风险;

(2)spring写法的

①、导入jar依赖(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.lj</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銆佸鍏pring渚濊禆 -->
		<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銆乯unit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- 5.2銆乻ervlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${javax.servlet.version}</version>
			<scope>provided</scope>
		</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>

②、导入xsd约束(spring-context.xml)

假如需要更新直接修改配置就可以了,不用修改原有代码;

如果更新错误回到更新前直接将userBiz2改为userBiz1即可;

<bean name="personAction" class="com.lj.ioc.web.PersonAction">
     <property name="userBiz" ref="userBiz2"></property>
</bean>

<?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">
 
<!--
    本文件中配置整个项目中包含的javabean,目的在于spring统一管理
  -->
<bean name="userBiz1" class="com.lj.ioc.biz.impl.UserBizImpl1"></bean>
<bean name="userBiz2" class="com.lj.ioc.biz.impl.UserBizImpl2"></bean>
<bean name="personAction" class="com.lj.ioc.web.PersonAction">
     <property name="userBiz" ref="userBiz2"></property>
</bean>
<bean name="userAction" class="com.lj.ioc.web.UserAction"></bean>
 
</beans>

③、测试及结果

package com.lj.ioc.web;
/**
 *这个使用第二个版本
 */
import com.lj.ioc.biz.UserBiz;
import com.lj.ioc.biz.impl.UserBizImpl1;
import com.lj.ioc.biz.impl.UserBizImpl2;
public class PersonAction {
//	原始写法
//	private UserBiz userBiz=new UserBizImpl2();
	
	//spring写法
	private UserBiz userBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
 
	
	public void upload() {
		userBiz.upload();
	}
	
}

main测试 

package com.lj.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lj.ioc.web.PersonAction;
import com.lj.ioc.web.ParamAction;
/**
 *测试类
 */
public class IocTest {
	public static void main(String[] args) {
		//第一步:对spring-context.xml文件进行建模
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		PersonAction personAction = (PersonAction)applicationContext.getBean("personAction");
		personAction.upload();		
	}
}

得到结果:

 2、spring传参

给javabean赋初始化值  传参
(1)、set传参
(2)、构造传参
(3)、自动装配(基本不用)

①、set传参

ParamAction :

package com.lj.ioc.web;
import java.util.List;
public class PersonAction {
	private int age;
	private String name;
	private List<String> hobby;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<String> getHobby() {
		return hobby;
	}
	public void setHobby(List<String> hobby) {
		this.hobby = hobby;
	}
	
	public void execute() {
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
 
	}
}

测试:

package com.lj.ioc.test;

import org.aspectj.apache.bcel.classfile.ClassParser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lj.ioc.web.PersonAction;
import com.lj.ioc.web.UserAction;
import com.lj.ioc.web.UserAction2;
import com.lj.ioc.web.UserAction3;

public class IocTest2 {
public static void main(String[] args) {
	//建模
	ApplicationContext a=new ClassPathXmlApplicationContext("/spring-context.xml");
    PersonAction bean = (PersonAction) a.getBean("personAction");
    bean.execute();
}
}

结果:

②、构造传参

ParamAction :

package com.lj.ioc.web;
import java.util.List;
public class ParamAction {
	private int age;
	private String name;
	private List<String> hobby;
	public ParamAction() {
		// TODO Auto-generated constructor stub
	}
	
	public void execute() {
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
 
	}
 
	public ParamAction(int age, String name, List<String> hobby) {
		super();
		this.age = age;
		this.name = name;
		this.hobby = hobby;
	}
}

 配置(spring-context.xml)

<bean name="paramAction" class="com.lj.ioc.web.ParamAction">
     <constructor-arg name="name" value="lj"></constructor-arg>
     <constructor-arg name="age" value="20"></constructor-arg>
     <constructor-arg name="hobby">
          <list>
               <value>a</value>
               <value>b</value>
          </list>
     </constructor-arg>
</bean>

测试

package com.lj.ioc.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lj.ioc.web.PersonAction;
import com.lj.ioc.web.ParamAction;
/**
 *测试类
 */
public class IocTest {
	public static void main(String[] args) {
		//第一步:对spring-context.xml文件进行建模
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction paramAction = (ParamAction)applicationContext.getBean("paramAction");
		paramAction.execute();
		
	}
}

结果

 

3、spring和Tomcat整合 

假如spring-context.xml中配置了几百个类,测试建模的时间过程非常久;

javabean每建一次模,时间就越久,性能就越差;

这行代码会执行很久,所以说这行代码在项目中只能执行一次,将他放到监听器中

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");

1、监听器:SpringLoaderListener实现 ServletContextListener接口

package com.lj.ioc.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringLoaderListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//这个方法有且只会执行一次,Tomcat启动执行一次就不会在执行了
		System.out.println("监听器方法执行----");
		//将建模的过程放到监听器中执行
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("/spring-context.xml");
		//在将他保存到Tomcat上下文中;
		sce.getServletContext().setAttribute("SpringContext", applicationContext);
		
	}
}

2、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>
  
  <listener>
        <listener-class>com.lj.ioc.listener.SpringLoaderListener</listener-class>
  </listener>
  
</web-app>

3、测试及结果

①、测试UserServlet 

package com.lj.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 service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ApplicationContext springContext = (ApplicationContext) req.getServletContext().getAttribute("SpringContext");
		ParamAction paramAction = (ParamAction) springContext.getBean("paramAction");
		paramAction.execute();
	}
}

②、结果:监听器只会执行一次,结果可执行多次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值