目录
2.2.4 创建Spring的配置文件application.xml
需要在 Spring 配置文件中配置组件扫描器,用于在指定的基本包中扫描注解。如果没有报扫描,添加的创建对象的注解不生效。
2.5.5 byName自动注入@Autowired和@Qualifier
一 :Spring概述
1.1 什么是框架?
框架(Framework):框(指其约束性)架(指其支撑性),在软件设计中指为解决一个开放性问题而设计的具有一定约束性的支撑结构。在此结构上可以根据具体问题扩展、安插更多的组成部分,从而更迅速和方便地构建完整的解决问题的方案。
(1)框架本身一般不完整但可以解决特定问题
(2)框架天生就是为扩展而设计的
(3)框架里面可以为后续扩展的组件提供很多辅助性、支撑性的方便易用的实用具 (utilities),也就是说框架时常配套了一些帮助解决某类问题的库(libraries)或工具(tools)。
1.2 Spring是什么
Spring官网 Spring | Home
(1) Spring 被称为 J2EE 的春天,是一个是分层的 Java SE/EE full-stack 开源的轻量级的 Java 开发框架, 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用 Spring 框架来创建性能好、易于测试、可重用的代码。
(2) Spring具有控制反转(IoC)和面向切面(AOP)两大核心。Java Spring 框架通过声明式方式灵活地进行事务的管理,提高开发效率和质量。
(3) Spring 框架不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何 Java 应用都可以从 Spring 中受益。Spring 框架还是一个超级粘合平台,除了自己提供功能外,还提供粘合其他技术和框架的能力。
1.3 Spring的优势
1、方便解耦,简化开发
Spring就是一个大工厂,可以将所有对象的创建和依赖关系的维护交给Spring管理。
2、方便集成各种优秀框架
Spring不排斥各种优秀的开源框架,其内部提供了对优秀框架(如Struts2、Hibernate、 MyBatis等)的直接支持
3、降低JavaEE API的使用难度
Spring对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等)都提供了 封装,使这些API应用的难度大大降低。
4、方便程序的测试
Spring支持JUnit4,可以通过注解方便地测试Spring程序。
5、AOP编程的支持
Spring提供面向切面编程,可以方便的实现对程序进行权限拦截和运行监控等功能
6、声明式事务的支持
只需要通过配置就可以完成对事务的管理,而无须手动编程。
1.4 Spring的体系结构
Spring 为我们提供了一站式解决方案,但Spring 是模块化的,允许咱们挑选和选择适用于项目的模块,不需要把剩余部分也引入。
Spring 框架提供约 20 个模块,可以根据应用程序的要求来选择。
1.4.1 核心容器
核心容器由 Spring-core,Spring-beans,Spring-context,Spring-context-support Spring-expression(SpEL,Spring 表达式语言,Spring Expression Language)等模块组成
(1)Spring-core 模块提供了框架的基本组成部分,包括 IoC 和依赖注入功能。
(2)Spring-beans 模块提供 BeanFactory,工厂模式的微妙实现,它移除了编码式单例的 需要,并且可以把配置和依赖从实际编码逻辑中解耦。
(3)context 模块建立在由 core和 beans 模块的基础上建立起来的,它以一种类似于 JNDI 注册的方式访问对象。Context 模块继承自 Bean 模块,并且添加了国际化(比如,使用资源束)、事件传播、资源加载和透明地创建上下文(比如,通过 Servelet 容器)等功能。Context 模块也支持 JavaEE 的功能,比如 EJB、JMX 和远程调用等 ApplicationContext 接口是 Context 模块的焦点。
(4)Spring-context-support 提供了对第三方集成到 Spring 上下文的支持,比如缓存(EhCache,Guava, JCache)、邮件(JavaMail)、调度(CommonJ, Quartz)、模板引擎(FreeMarker,JasperReports, Velocity)等。
(5)Spring-expression 模块提供了强大的表达式语言,用于在运行时查询和操作对象图。它是 JSP2.1规范中定义的统一表达式语言的扩展,支持 set 和 get 属性值、属性赋值、方法调用、访问数组集合及索引的内容、逻辑算术运算、命名变量、通过名字从 Spring IoC 容器检索对象,还支持列表的投影、选择以及聚合等。
它们的完整依赖关系如下图所示:
1.4.2 数据访问/集成
JDBC=Java Data Base Connectivity,ORM=Object Relational Mapping,
OXM=Object XML Mapping,JMS=Java Message Service
(1)JDBC 模块提供了 JDBC 抽象层,它消除了冗长的 JDBC 编码和对数据库供应商特定错误代码的解析。
(2)ORM 模块提供了对流行的对象关系映射 API 的集成,包括 JPA、JDO 和 Hibernate 等。通过此模块可以让这些 ORM 框架和 Spring的其它功能整合,比如前面提及的事务管理。
(3)OXM 模块提供了对 OXM 实现的支持,比如 JAXB、Castor、XML Beans、JiBX、XStream 等
(4)JMS 模块包含生产(produce)和消费(consume)消息的功能。从 Spring 4.1 开始,集成了Spring-messaging 模块。
(5)事务模块为实现特殊接口类及所有的 POJO 支持编程式和声明式事务管理
1.4.3 Web
(1)Web 模块提供面向 web 的基本功能和面向 web 的应用上下文,比如多部(multipart)文件上传功能、使用 Servlet 监听器初始化 IoC 容器等。它还包括 HTTP 客户端以及 Spring 远程调用中与web 相关的部分。
(2)Web-MVC 模块为 web 应用提供了模型视图控制(MVC)和 REST Web服务的实现。Spring 的MVC 框架可以使领域模型代码和 web 表单完全地分离,且可以与 Spring 框架的其它所有功能进行集成。
(3)Web-Socket 模块为 WebSocket-based 提供了支持,而且在 web 应用程序中提供了客户端和服务器端之间通信的两种方式。
(4)Web-Portlet 模块提供了用于 Portlet 环境的 MVC 实现,并反映了 Spring-webmvc 模块的功能。
1.4.4 其他
(1)AOP 模块提供了面向方面(切面)的编程实现,允许你定义方法拦截器和切入点对代码进行干净地解耦,从而使实现功能的代码彻底的解耦出来。
(2)Aspects 模块提供了与 AspectJ 的集成,这是一个功能强大且成熟的面向切面编程(AOP)框架。
(3)Instrumentation 模块在一定的应用服务器中提供了类 instrumentation 的支持和类加载器的实现。
(4)Messaging 模块为 STOMP 提供了支持作为在应用程序中 WebSocket 子协议的使用。它也支持一个注解编程模型,它是为了选路和处理来自 WebSocket 客户端的 STOMP 信息。
(5)测试模块支持对具有 JUnit 或 TestNG 框架的 Spring 组件的测试。
二 : Spring核心之IoC控制反转
2.1 IoC的概念
IoC 是指在程序开发中,实例的创建不再由调用者管理,而是由 Spring 容器创建。Spring 容器会负责控制程序之间的关系,而不是由程序代码直接控制,因此,控制权由程序代码转移到了 Spring 容器中,控制权发生了反转,这就是 Spring 的 IoC 思想。
2.2 Spring入门案例
2.2.1 创建maven项目
创建完毕的目录结构
2.2.2 pom.xml文件添加依赖和插件
<dependencies>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
注意!!!这个编译插件的代码块必须写,如果不写就会报错
2.2.3 创建一个实体类
package com.kkb.pojo;
/**
* 实体类球队
*/
public class Team {
private Integer id;
private String name;
private String location;
public Team() {
System.out.println("Team的默认构造方法被调用:id="+id+",name="+name+",
location="+location);
}
}
2.2.4 创建Spring的配置文件application.xml
注意!!!如果此时没有Spring Config的话 请参照此网站配置一下
IDEA 没有spring config ,4层解决方法_SolarisNeko的博客-CSDN博客_idea没有config文件
将此XML文件命名为application.xml
2.2.5 使用Spring容器创建对象
<?xml version="1.0" encoding="UTF-8"?>
<!--spring的配置文件
1、beans: 根标签,spring中java的对象成为bean
2、spring-beans.xsd 是约束文件(约束XML文件中能编写哪些标签)-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建对象:声明bean,通知spring要创建哪个类的对象
一个bean标签声明一个对象:
id="自定义的对象名称" ,要求唯一
class="类的完全限定名" 包名+类名,spring底层是反射机制创建对象,所以必须使用类名
相当于 Team team1=new Team();创建好的对象放入一个集合Map中
例如:springMap.put("team1",new Team());
-->
<bean id="team1" class="com.kkb.pojo.Team"></bean>
</beans>
2.2.6 获取Spring容器
Spring 提供了两种 IoC 容器,分别为 BeanFactory 和 ApplicationContext.
(1)BeanFactory
BeanFactory 是基础类型的 IoC 容器,是一个管理 Bean 的工厂,它主要负责初始化各种 Bean,并调用它们的生命周期方法。
BeanFactory 接口有多个实现类,最常见的是
org.Springframework.beans.factory.xml.XmlBeanFactory,它是根据 XML 配置文件中的定义装配
Bean 的。
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource(Spring配置文件
的名称));
(2) ApplicationContext
ApplicationContext 是 BeanFactory 的子接口,也被称为应用上下文。它不仅提供了 BeanFactory 的所有功能,还添加了对 i18n(国际化)、资源访问、事件传播等方面的良好支持。
ApplicationContext 接口有两个常用的实现类:
One :ClassPathXmlApplicationContext——常用
该类从类路径 ClassPath 中寻找指定的 XML 配置文件,找到并装载完成 ApplicationContext 的实例化工作
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(Spring配
置文件的名称);
Two : FileSystemXmlApplicationContext
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation);
比较--两者区别:
在读取 Spring 的配置文件时,FileSystemXmlApplicationContext 不再从类路径中读取配置文件,而是通过参数指定配置文件的位置,它可以获取类路径之外的资源,如“D:\application.xml”。
2.2.7 通过上下文对象获取容器中的对象
package com.kkb.test;
import com.kkb.pojo.Team;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import java.util.Date;
public class Test1 {
@Test
public void test01(){
//使用spring容器创建对象
//1、指定spring配置文件的名称
String springConfig="application.xml";
//2、创建spring容器的对象:
//方式1:不推荐,了解
//BeanFactory beanFactory = new XmlBeanFactory(new
FileSystemResource("D:/workspaces/ideaProjects/MySpring/spring01/src/main/resour
ces/application.xml"));
//beanFactory.getBean("team1");//根据ID从IOC容器获取对象
//方式2:applicationContext--常用
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext(springConfig);//这里执行完毕容器中的对象都已经创建完成
//方式3:applicationContext--了解
//ApplicationContext applicationContext2 = new
FileSystemXmlApplicationContext("D:/workspaces/ideaProjects/MySpring/spring01/sr
c/main/resources/application.xml");
//3、获取容器中的对象
Team team1= (Team) applicationContext.getBean("team1");
//4、容器其他api
int beanDefinitionCount = applicationContext.getBeanDefinitionCount();
System.out.println("spring容器中对象的个数:"+beanDefinitionCount);
String[] beanDefinitionNames =applicationContext.getBeanDefinitionNames();
System.out.println("spring容器中所有对象的名称:");
for (String name : beanDefinitionNames) {
System.out.println(name);
}
}
}
2.2.8 在pom.xml文件中创建非自定义对象
pox.xml文件中补充
<!--创建非自定义的对象-->
<bean id="date" class="java.util.Date"></bean>
上面的测试方法中添加如下内容:
//5、获取日期对象
Date date1= (Date) applicationContext.getBean("date1");
System.out.println("日期:"+date1);
2.2.9 bean标签的属性
属性 | 说明 |
class | 指定bean对应类的全路径 |
name | name是bean对应对象的一个标识 |
scope | 执行bean对象创建模式和生命周期,scope="singleton"和scope="prototype" |
id | id是bean对象的唯一标识,不能添加特别字符 |
lazy-init | 是否延时加载 默认值:false。true 延迟加载对象,当对象被调用的时候才会加载,测试的时候,通过getbean()方法获得对象。lazy-init="false" 默认值,不延迟,无论对象是否被使用,都会立即创建对象,测试时只需要加载配置文件即可。注意:测试的时候只留下id,class属性 |
init-method | 只需要加载配置文件即可对象初始化方法 |
destroy-method | 对象销毁方法 |
示例演示:
准备:在Team实体类补充如下方法:
package com.kkb.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Team {
private Integer id;
private String name;
private String location;
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
public Team(){
System.out.println("Team - 默认方法 id="+id+",name="+name+",location="+location);
}
public Team(Integer id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
System.out.println("Team - 带参数的构造方法
id="+id+",name="+name+",location="+location);
}
public void init(){
System.out.println("初始化");
}
public void destroy(){
System.out.println("销毁");
}
}
application.xml配置文件添加如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!--spring配置文件
beans:根标签
spring中java的对象成为java bean
spring-beans.xsd是一个约束文件,约束xml文件中都能编写那些标签-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建对象:声明bean,告知spring容器创建那些对象
scope="singleton/prototype"
singleton:单例,默认值,容器启动完毕之后单例对象就被创建了,而且容器中只有一个唯一对象
prototype:多例,多例对象是什么时候使用什么时候创建,每次获取的时候都创建新对象
lazy-init="true/false" 是否加载针对单例对象
true:真懒 获取对象的时候才创建对象
false:不懒 立即创建对象,不管是否使用
生命周期相关:
init-method="对象创建完毕之后立即调用初始化方法"
destroy-method="spring容器调用关闭方法时执行的方法"
-->
<bean id="team1" class="com.kkb.pojo.Team" scope="singleton" lazy-init="false" init-method="init" destroy-method="destroy"></bean>
<bean id="team2" class="com.kkb.pojo.Team" scope="prototype"></bean>
<bean id="date1" class="java.util.Date"></bean>
</beans>
编写测试类:
这里使用ClassPathXmlApplicationContext作为父类而不是ApplicationContext
因为ApplicationContext没有定义close方法
@Test
public void test02(){
//spring容器创建对象的方式
String springConfig="application.xml";
//获取容器
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(springConfig);
//从容器中根据id获取对象
Team team1 = (Team) applicationContext.getBean("team1");
Team team11 = (Team) applicationContext.getBean("team1");
System.out.println(team1.equals(team11));
Team team2 = (Team) applicationContext.getBean("team2");
Team team22 = (Team) applicationContext.getBean("team2");
System.out.println(team2.equals(team22));
applicationContext.close();//关闭容器
}
运行结果:
2.3 Spring容器创建对象的方式
2.3.1 使用默认的构造方法
<bean id="team1" class="com.kkb.pojo.Team"></bean>
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("createType.xml");
}
在对象创建时,会调用对象的无参构造方法
2.3.2 使用带参数的构造方法
Team类:
xml文件中:
<!--2.通过带参数的构造方法-->
<bean id="team2" class="com.kkb.pojo.Team">
<!--name:表示参数的名称-->
<constructor-arg name="id" value="1001"/>
<constructor-arg name="name" value="勇士"/>
<constructor-arg name="location" value="金州"/>
</bean>
<bean id="team3" class="com.kkb.pojo.Team">
<!--index:表示参数的下标索引-->
<constructor-arg index="0" value="1002"/>
<constructor-arg index="1" value="热火"/>
<constructor-arg index="2" value="迈阿密"/>
</bean>
测试类:
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("createType.xml");
}
输出:
2.3.3 使用工厂类
已知上面创建了Team的有参构造方法
创建工厂类:
package com.kkb.pojo;
public class MyFactory {
/**
* 实例方法
* @return
*/
public Team instanceFun(){
System.out.println("MyFactory-----instanceFun");
return new Team(1003,"湖人","洛杉矶");
}
/**
* 静态方法
* @return
*/
public static Team staticFun(){
System.out.println("MyFactory-----staticFun");
return new Team(1004,"小牛","达拉斯");
}
public static void main(String[] args) {
Team team1 = MyFactory.staticFun();
MyFactory factory = new MyFactory();
Team team = factory.instanceFun();
}
}
创建新的配置文件createType.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--3.通过工厂方法:
3.1 静态方法 Team team1 = MyFactory.staticFun(); -->
<bean id="staticTeam" class="com.kkb.pojo.MyFactory" factory-method="staticFun"></bean>
<!--3.通过工厂方法:
3.2 实例方法
MyFactory factory = new MyFactory();
Team team = factory.instanceFun();-->
<bean id="factory" class="com.kkb.pojo.MyFactory"></bean>
<bean id="instance" factory-bean="factory" factory-method="instanceFun"></bean>
</beans>
测试类:
运行结果:
2.4 基于XML的DI
概念:
DI—Dependency Injection,即“依赖注入”:是组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能,而是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。
IoC 是一个概念,是一种思想,其实现方式多种多样。依赖注入就是其中用的比较多的一种方式。
Ioc和DI是同一个概念的不同角度描述。IoC是一种思想,概念,DI是实现它的手段。Spring框架使用依赖注入实现IoC。
Spring 容器是一个超级大工厂,负责创建、管理所有的 Java 对象,这些 Java 对象被称为 Bean。Spring 容器管理着容器中 Bean 之间的依赖关系,Spring 使用“依赖注入”的方式来管理 Bean 之间的依赖关系。使用 IoC 实现对象之间的解耦和。
2.4.1 注入分类
bean 实例在调用无参构造器创建对象后,就要对 bean 对象的属性进行初始化。初始化是由容器自动完成的,称为注入。
2.4.1.1 通过set方法
set 注入也叫设值注入,是指通过 setter 方法传入被调用者的实例。这种注入方式简单、直观,因而在Spring 的依赖注入中大量使用。
举例测试: 先创建Dao类和Service类 并提供方法
Dao类:
public class TeamDao {
public TeamDao() {
System.out.println("TeamDao ---- 默认的构造方法");
}
}
Service类:
public class TeamService {
private TeamDao teamDao;// 只需要给出声明,对象的创建交给spring完成
public TeamService() {
System.out.println("TeamService---默认构造方法");
}
// 必须提供get和set方法!!!
public TeamDao getTeamDao() {
return teamDao;
}
public void setTeamDao(TeamDao teamDao) {
this.teamDao = teamDao;
}
}
创建配置类DI.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
<bean id="teamService" class="com.kkb.service.TeamService">
<!--使用set方法注入属性值-->
<property name="teamDao" ref="teamDao"></property>
</bean>
</beans>
编写测试类:
@Test
public void test03(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
}
测试结果:
2.4.1.2 通过构造方法
构造注入是指,在构造调用者实例的同时,完成被调用者的实例化。使用构造器设置依赖关系。
在TeamService中添加有参构造方法:
package com.kkb.service;
import com.kkb.dao.TeamDao;
public class TeamService {
private TeamDao teamDao;// 只需要给出声明,对象的创建交给spring完成
public TeamService() {
System.out.println("TeamService---默认构造方法");
}
// 带有参数的构造方法
public TeamService(TeamDao teamDao) {
System.out.println("TeamService---含参构造方法");
this.teamDao = teamDao;
}
}
修改配置文件DI.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
<bean id="teamService2" class="com.kkb.service.TeamService">
<!--使用构造方法注入属性值-->
<constructor-arg name="teamDao" ref="teamDao"></constructor-arg>
</bean>
</beans>
测试类进行测试:
@Test
public void test03(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
}
测试结果:
2.4.1.3 自动注入
对于引用类型属性的注入,也可不在配置文件中显示的注入。
可以通过为标签设置 autowire 属性值,为引用类型属性进行隐式自动注入(默认是不自动注入引用类型属 性)。根据自动注入判断标准的不同,可以分为两种:
1. byName:根据名称自动注入
当配置文件中被调用者 bean 的 id 值与代码中调用者 bean 类的属性名相同时,可使用byName 方式,让容器自动将被调用者 bean 注入给调用者 bean。容器是通过调用者的 bean类的属性名与配置文件的被调用者 bean 的 id 进行比较而实现自动注入的。
2. byType: 根据类型自动注入
使用 byType 方式自动注入,要求:配置文件中被调用者 bean 的 class 属性指定的类,要与代码中调用者 bean 类的某引用类型属性类型同源。即要么相同,要么有 is-a 关系(子类,或是实现类)。但这样的同源的被调用 bean 只能有一个。多于一个,容器就不知该匹配哪一个了。
(1)byName示例:
修改配置类DI.xml: 在bean标签中增加autowire属性
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
<!--按名称自动注入:查找容器中id名与属性名一致的对象进行注入-->
<bean id="teamService" class="com.kkb.service.TeamService" autowire="byName"></bean>
</beans>
在这里被调用者是teamDao,调用者为teamService。
运行测试方法:
@Test
public void test03(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
}
测试结果:
(2)byType示例:
修改配置类DI.xml: 在bean标签中增加autowire属性
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
<!--按类型自动注入:查找容器中类型与属性类型相同或者符合is-a关系的对象进行注入,但是要求类型相同的对象唯一,否则抛出异常:不知道用哪一个匹配-->
<bean id="teamService" class="com.kkb.service.TeamService" autowire="byType"></bean>
</beans>
在这里被调用者是teamDao,调用者为teamService。
运行测试方法:
@Test
public void test03(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
}
运行结果:
2.5 基于注解实现IoC--重要
对于 DI 使用注解,将不再需要在 Spring 配置文件中声明 bean 实例。Spring 中使用注解,需要在原有Spring 运行环境基础上再做一些改变。
2.5.1 声明Bean的注解 @Component
在类上添加注解@Component表示该类创建对象的权限交给Spring容器。注解的value属性用于指定bean的id值,value可以省略。
@Component 不指定 value 属性,bean 的 id 是类名的首字母小写。
@Component(value="teamDao")
@Component("teamDao")
@Component // 默认类名首字母小写
//@Component 注解标识在类上,表示对象由Spring容器创建 value属性表示创建的id值,value可以省略,值也可省略,默认就是类名的首字母小写
@Component(value="teamDao")
// 相当于xml文件中的额<bean id="teamDao" class="com.kkb.dao.TeamDao"></bean>
public class TeamDao {
public void add(){
System.out.println("TeamDao---- add----");
}
public TeamDao() {
System.out.println("TeamDao ---- 默认的构造放方法");
}
}
除此之外,Spring中还提供了其他3个用于创建对象的注解:
1. @Repository : 用于dao实现类的的注解
2. @Service: 用户service实现类的注解
3. @Controller: 用于controller实现类的注解
这三个注解与@Component 都可以创建对象,但这三个注解还有其他的含义,@Service创建业务层对象,业务层对象可以加入事务功能,@Controller 注解创建的对象可以作为处理器接收用户的请求。
@Repository,@Service,@Controller 是对@Component 注解的细化,标注不同层的对象。即持久层对象,业务层对象,控制层对象。
2.5.2 包扫描
需要在 Spring 配置文件中配置组件扫描器,用于在指定的基本包中扫描注解。如果没有报扫描,添加的创建对象的注解不生效。
如果要扫描的包有多个,可以有以下方式扫描:
1、使用多个context:component-scan指定不同的包路径
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--表示告知spring 要扫描的包
这些包以及子包当中的类上如果添加了@Component注解,这些添加了注解的类就交给了spring容器创建对象-->
<!--多个包的扫描 方式1 <context:component-scan 表明-->
<context:component-scan base-package="com.kkb.dao"></context:component-scan>
<context:component-scan base-package="com.kkb.service"></context:component-scan>
<context:component-scan base-package="com.kkb.controller"></context:component-scan>
</beans>
2、指定 base-package的值使用分隔符
分隔符可以使用逗号(,)分号(;)还可以使用空格,不建议使用空格。
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--表示告知spring 要扫描的包
这些包以及子包当中的类上如果添加了@Component注解,这些添加了注解的类就交给了spring容器创建对象-->
<!--多个包的扫描 方式2 base-package中直接声明要扫描的多个包, 多个值用逗号,分号或者空格分割-->
<context:component-scan base-package="com.kkb.dao,com.kkb.service,com.kkb.controller"></context:component-scan>
</beans>
3、base-package是指定到父包名
base-package 的值表是基本包,容器启动会扫描包及其子包中的注解,当然也会扫描到子包下级的子包。所以 base-package 可以指定一个父包就可以。
但不建议使用顶级的父包,扫描的路径比较多,导致容器启动时间变慢。指定到目标包和合适的。也就是注解所在包全路径。
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--表示告知spring 要扫描的包
这些包以及子包当中的类上如果添加了@Component注解,这些添加了注解的类就交给了spring容器创建对象-->
<!--多个包扫描 方式3 base-package中直接声明要扫描的多个包的父包-->
<context:component-scan base-package="com.kkb"></context:component-scan>
</beans>
2.5.3 属性注入@Vaule
需要在属性上使用注解@Value,该注解的 value 属性用于指定要注入的值。使用该注解完成属性注入时,类中无需 setter。当然,若属性有 setter,则也可将其加到 setter 上。
package com.kkb.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Team {
private Integer id;
private String name;
@Value("洛杉矶")
private String location;
@Value("1001")
public void setId(Integer id) {
this.id = id;
}
@Value("湖人")
public void setName(String name) {
this.name = name;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
public Team(){
System.out.println("Team - 默认方法 id="+id+",name="+name+",location="+location);
}
public Team(Integer id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
System.out.println("Team - 带参数的构造方法
id="+id+",name="+name+",location="+location);
}
public void init(){
System.out.println("初始化");
}
public void destroy(){
System.out.println("销毁");
}
}
2.5.4 byType自动注入@Autowired
需要在引用属性上使用注解@Autowired,该注解默认使用按类型自动装配 Bean 的方式。使用该注解完成属性注入时,类中无需 setter。当然,若属性有 setter,则也可将其加到 setter 上。
2.5.5 byName自动注入@Autowired和@Qualifier
需要在引用属性上联合使用注解@Autowired 与@Qualifier。
@Qualifier 的 value 属性用于指定要匹配的 Bean 的 id 值。类中无需 set 方法,也可加到 set 方法上。
@Autowired 还有一个属性 required,默认值为 true,表示当匹配失败后,会终止程序运行。若将其值设置为 false,则匹配失败,将被忽略,未匹配的属性值为 null。
@Service
public class TeamService {
@Autowired //自动装配 默认按照类型装配 @Autowired(required=true/false)
//@Qualifier(“teamDao”) //按照名字自动装配 需要Qualifier搭配使用
private TeamDao teamDao;
2.5.6 自动注入@Resource
Spring提供了对 jdk中@Resource注解的支持。@Resource 注解既可以按名称匹配Bean,也可以按类型匹配 Bean。默认是按名称注入。使用该注解,要求 JDK 必须是 6 及以上版本。@Resource 可在属性上,也可在 set 方法上。
(1)byType注入引用类型属性
@Resource 注解若不带任何参数,采用默认按名称的方式注入,若按名称不能注入 bean,则会按照类型进行 Bean 的匹配注入。
(2)byName注入引用类型属性
@Resource 注解指定其 name 属性,则 name 的值即为按照名称进行匹配的 Bean 的 id。
package com.kkb.controller;
import com.kkb.service.TeamService;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
@Controller
public class TeamController {
@Resource //JDK版本高于1.6 自动装配默认按名称 但是如果名称没有 就按照类型自动装配 JDK给的注解
private TeamService teamService;
public void add(){
teamService.add();
System.out.println("TeamController --------add--");
}
public TeamController() {
System.out.println("TeamController----- 默认构造方法");
}
}
@Controller
public class TeamController {
@Resource(name="teamService1",type = TeamService.class) //JDK版本高于1.6 自动装配默认按照名称 但是如果名称没有相符的,就按照类型自动装配
private TeamService teamService;
public void add(){
teamService.add();
System.out.println("TeamController---- add ----");
}
public TeamController() {
System.out.println("TeamController ---- 默认的构造放方法");
}
}
三、Spring核心之AOP
3.1 什么是AOP
AOP为Aspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP的作用:不修改源码的情况下,程序运行期间对方法进行功能增强
好处:1、减少代码的重复,提高开发效率,便于维护。
2、专注核心业务的开发。
核心业务和服务性代码混合在一起
开发中:各自做自己擅长的事情,运行的时候将服务性代码织入到核心业务中。
通过spring工厂自动实现将服务性代码以切面的方式加入到核心业务代码中。
3.2 AOP的实现机制-动态代理
3.2.1 什么是代理模式
代理:自己不做,找人帮你做。
代理模式:在一个原有功能的基础上添加新的功能。
分类:静态代理和动态代理。
3.3 静态代理
3.3.1 原有方式:核心业务和服务方法都编写在一起
public class TeamService {
public void add(){
try {
System.out.println("开始事务");
System.out.println("TeamService---- add----");// 核心业务
System.out.println("提交事务");
} catch (Exception e) {
e.printStackTrace();
System.out.println("回滚事务");
}
}
}
3.3.2 基于静态的代理
将服务性代码分离出来,核心业务--保存业务中只有保存功能
被代理类:
package com.kkb.service;
public class TeamService {
public void add(){
System.out.println("TeamService---- add----");// 核心业务
}
}
代理类:
package com.kkb.service.staticproxy;
import com.kkb.service.TeamService;
/**
* 基于类的静态代理
* 要求继承被代理的类
* 弊端:每次只能代理一个类
*/
public class ProxyTeamService extends TeamService {
public void add(){
try{
System.out.println("开始事务");
super.add();//核心业务就是被代理对象完成的 其他服务功能由代理类实现
System.out.println("提交事务");
}catch (Exception e){
System.out.println("回滚事务");
}
}
}
利用super关键字在子类中调用父类的方法
主方法测试程序:
public static void main(String[] args) {
TeamService ser=new ProxyTeamService();
ser.add();
}
这样的静态代理有一个弊端就是一次只能代理一个类,如果需要代理的类多了起来就会非常麻烦。
3.3.3 基于接口的静态代理
为核心业务(保存add)创建一个接口,通过接口暴露被代理的方法
要求:代理类和被代理类都实现了同一个接口
优点:1. 代理类与被代理类解耦。相比基于类的静态代理,一个代理类只要传入不同的参 数,就可以代理不同的类。
2. 由于代理类与被代理类松耦合,因此可以方便的实现多级代理。
接口:
/**
* 接口定义核心方法
*/
public interface IService {
void add();
}
被代理类:
// 被代理类1
public class TeamService implements IService{
@Override
public void add(){
System.out.println("TeamService---- add----");// 核心业务
}
}
// 被代理类2
public class UserService implements IService{
@Override
public void add() {
System.out.println("UserService---- add-----");
}
}
代理类:
事务代理类:
/**
* 基于接口的静态代理:
* 代理类和被代理类实现同一个接口
*/
public class ProxyTranService implements IService {
private IService service;//被代理的对象
public ProxyTranService(IService service) {
this.service = service;
}
@Override
public void add() {
try {
System.out.println("开始事务");
service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成
System.out.println("提交事务");
}catch (Exception e){
System.out.println("回滚事务");
}
}
}
日志代理类:
public class ProxyLogService implements IService {
private IService service;//被代理对象
public ProxyLogService(IService service) {
this.service = service;
}
@Override
public void add() {
try {
System.out.println("开始日志");
service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成
System.out.println("结束日志");
}catch (Exception e){
System.out.println("异常日志");
}
}
}
测试类:
public static void main(String[] args) {
TeamService teamService=new TeamService();//被代理对象
UserService userService=new UserService();//被代理对象
// 代理类与被代理类解耦。一个代理类,传入不同的参数,即可代理不同的类
ProxyTranService tranService=new ProxyTranService(userService);//事务代理对象--一级代理
// tranService.add();//代理对象干活
ProxyLogService logService=new ProxyLogService(tranService);//日志的代理对象--二级代理
logService.add();
}
测试结果:
3.3.4 提出切面代码,作为AOP接口
共有4个位置可以将切面代码编织进入核心业务代码中。
这样就可以简化代码,之前2个代理类,现在可化为一个代理类
切面接口:
/**
* 切面:服务代码,切入到核心代码中,切入到哪里,给了四个位置
*/
public interface AOP {
void before();
void after();
void exception();
void myFinally();
}
事务切面:
public class TranAOP implements AOP {
@Override
public void before() {
System.out.println("事务----before");
}
@Override
public void after() {
System.out.println("事务----after");
}
@Override
public void exception() {
System.out.println("事务----exception");
}
@Override
public void myFinally() {
System.out.println("事务----myFinally");
}
}
日志切面:
public class LogAop implements AOP{
@Override
public void before() {
System.out.println("日志----before");
}
@Override
public void after() {
System.out.println("日志----after");
}
@Override
public void exception() {
System.out.println("日志----exception");
}
@Override
public void myFinally() {
System.out.println("日志----myFinally");
}
}
代理类:
public class ProxyAOPService implements IService {
private IService service;//被代理对象
private AOP aop;//要加入切面
public ProxyAOPService(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public void add() {
try {
aop.before();
service.add();//被代理对象干活
aop.after();
}catch (Exception e){
aop.exception();
}finally {
aop.myFinally();
}
}
}
测试类:
@Test
public void test02(){
IService teamService=new TeamService();//被代理对象--核心内容
AOP logAop=new LogAop(); //日志切面-服务内容
AOP tranAop=new TranAOP(); //事务切面
IService service=new ProxyAOPService(teamService,logAop); //代理对象--一级代理
IService service2=new ProxyAOPService(service,tranAop);//代理对象--二级代理
service2.add();
}
测试结果:
总结静态代理:
(1)可以做到在不修改目标对象的功能前提下,对目标对象功能扩展。
(2)缺点:
因为代理对象,需要与目标对象实现一样的接口。所以会有很多代理类,类太多
一旦接口增加方法,目标对象与代理对象都要维护。
3.4 动态代理
动态代理是指代理类对象在程序运行时由JVM根据反射机制动态生成的。动态代理不需要定义代理类。动态代理其实就是jdk运行期间,动态创建class字节码并加载到JVM。
静态代理:要求代理类一定存在
动态代理:程序运行的时候,根据要被代理的对象动态生成代理类。
类型:1、基于JDK的动态代理
2、基于CGLIB的动态代理
3.4.1 基于JDK的动态代理
JDK动态代理的方法的基本介绍:
/*newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
ClassLoader :类加载器,因为动态代理类,借助别人的类加载器;一般使用被代理对象的类加 载器。
Class<?>[] interfaces:接口类对象的集合,针对接口的代理,针对哪个接口做代理,一般 使用的就是被代理对象的接口。
InvocationHandler:句柄,回调函数,编写代理的规则代码
public Object invoke(Object arg0, Method arg1, Object[] arg2)
Object arg0:代理对象
Method arg1:被代理的方法
Object[] arg2:被代理方法被执行的时候的参数的数组
*/
接口:
/**
* 接口定义核心方法
*/
public interface IService {
void add();
}
被代理类:
// 被代理类1
public class TeamService implements IService{
@Override
public void add(){
System.out.println("TeamService---- add----");// 核心业务
}
}
// 被代理类2
public class UserService implements IService{
@Override
public void add() {
System.out.println("UserService---- add-----");
}
}
使用JDK动态代理:
public class MyJDKProxy {
public static void main(String[] args) {
//目标对象--被代理对象
TeamService teamService=new TeamService();
//返回代理对象 调用JDK中Proxy类中的静态方法newProxyInstance获取动态代理类的实例
IService proxyService= (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
new InvocationHandler() {//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = method.invoke(teamService, args);//核心业务
System.out.println("提交事务");
return invoke;
}catch (Exception e){
System.out.println("回滚事务");
e.printStackTrace();
throw e;
}finally {
System.out.println("finally---------");
}
}
}
);
//代理对象干活
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass()+"--------");
}
}
测试结果:
可以看出上面并没有显式的创建代理类,代理类的创建工作交由jdk执行。
此外由于没有代理类的定义,因此代理类也不需要实现接口,所以接口变动时,只需要修改核心业务即可,动态代理对象的生成基本没有变动。
3.4.1.1 结构化设计
方式一:
先创建一个ProxyHandler类,实现InvocationHandler接口,重写invoke方法,不需要在newProxyInstance中重写invoke方法,看起来更简洁一些。
ProxyHandler类:
public class ProxyHandler implements InvocationHandler {
private IService service;//目标对象
private AOP aop;//切面
public ProxyHandler(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);//核心业务
aop.after();
return invoke;
}catch (Exception e){
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
测试类:
public static void main2(String[] args) {
//目标对象--被代理对象
TeamService teamService=new TeamService();
//切面
AOP tranAop=new TranAOP();
//返回代理对象 基于JDK的动态代理
IService proxyService= (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
new ProxyHandler(teamService,tranAop)
);
//代理对象干活
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass()+"------");
}
方法二:
手动创建一个ProxyFactory类,在其中创建方法并获得动态代理的实例
ProxyFactory类:
public class ProxyFactory {
private IService service;//目标对象
private AOP aop;//切面
public ProxyFactory(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
/**
* 获取动态代理的示例
* @return
*/
public Object getProxyInstance() {
return Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler() {//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);//核心业务
aop.after();
return invoke;
}catch (Exception e){
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
);
}
}
测试类:
public class MyJDKProxy {
public static void main(String[] args) {
//目标对象--被代理对象
TeamService teamService=new TeamService();
//切面
AOP tranAop=new TranAOP();
AOP logAop=new LogAop();
//获取代理对象
IService service= (IService) new ProxyFactory(teamService,tranAop).getProxyInstance();
IService service1= (IService) new ProxyFactory(service,logAop).getProxyInstance();
service1.add();//核心业务+服务代码混合在一起的完整的业务员方法
}
}
测试结果:
3.4.2 基于CGLIB的动态代理
Cglib代理,也叫做子类代理。在内存中构建一个子类对象从而实现对目标对象功能的扩展。
(1) JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。如 果想代理没有实现接口的类,就可以使用CGLIB实现。
(2) CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接 口。它广泛的被许多AOP的框架使用,例如Spring AOP和dynaop,为他们提供方法 的interception。
(3)CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成 新的类。不鼓励直接使用ASM,因为它要求你必须对JVM内部结构包括class文件的格 式和指令集都很熟悉。
编写测试类:
核心业务类:
public class NBAService {
public int add(String name,int id){
System.out.println("NBAService---- add----");
return id;
}
}
测试类:
public static void main(String[] args) {
//目标对象:没有接口
NBAService nbaService=new NBAService();
//创建代理对象:选择cglib动态代理
NBAService proxyService= (NBAService) Enhancer.create(nbaService.getClass(),
new MethodInterceptor() {//回调函数编写代理规则
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = methodProxy.invokeSuper(o, objects);//核心
System.out.println("提交事务");
return invoke;
} catch (Exception e){
System.out.println("事务回滚");
throw e;
} finally {
System.out.println("finally------------");
}
}
});
//代理对象干活
int res=proxyService.add("huren",1001);
System.out.println(res);
}
测试结果:
3.4.2.1 结构化设计
首先创建一个CGLIB的代理工厂类CglibProxyFactory:
public class CglibProxyFactory {
//目标对象
private NBAService nbaService;//没有实现接口的
//切面
private AOP aop;//切面
/**
* 创建代理对象
* @param nbaService
* @param aop
* @return
*/
public Object getProxyInstance(NBAService nbaService,AOP aop){
return Enhancer.create(nbaService.getClass(),
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
aop.before();
Object o1 = methodProxy.invokeSuper(o, objects);
aop.after();
return o1;
} catch (Exception e){
aop.exception();
throw e;
} finally {
System.out.println("finally-----------");
}
}
});
}
}
测试类:
public static void main1(String[] args) {
//目标对象 没有接口
NBAService nbaService = new NBAService();
//创建切面
AOP aop = new TranAop();
//创建代理对象,选择cglib动态代理
NBAService proxyInstance = (NBAService) new CglibProxyFactory().getProxyInstance(nbaService, aop);
int res = proxyInstance.add("湖人", 1001);
System.out.println(res);
}
测试结果:
3.4.3 JDK代理和CGLIB代理不同之处
(1)创建代理对象的方法上
JDK代理:
// 返回指定接口的代理实例,该接口将方法调用分派给指定的调用处理程序。
Proxy.newProxyInstance(ClassLoader loader, 类<?>[] interfaces, InvocationHandler h);
Proxy.newProxyInstance(service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler(){...}
);
基于CGLIB代理:
Enhancer.create(service.getClass(), new MethodInterceptor(){...});
(2)回调函数的方法上
基于JDK(回调函数InvocationHandler中重写invoke方法)
invoke(Object proxy, Method method, Object[] args)
new InvocationHandler() {//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
Object invoke = method.invoke(service, args);//核心业务
aop.after();
return invoke;
}catch (Exception e){
aop.exception();
e.printStackTrace();
throw e;
}finally {
aop.myFinally();
}
}
}
基于CGLIB(回调函数MethodInterceptor中重写intercept方法)
intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
aop.before();
Object o1 = methodProxy.invokeSuper(o, objects);
aop.after();
return o1;
}catch (Exception e){
aop.exception();
throw e;
} finally {
System.out.println("finally-----------");
}
}
}
(3)核心业务处理
基于JDK:
Object invoke = method.invoke(service, args);//核心业务
基于CGLIB:
Object o1 = methodProxy.invokeSuper(o, objects);
3.5 SpringAOP
3.5.1 SpringAOP相关概念
Spring的AOP实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
我们先来介绍AOP的相关术语:
Target(目标对象):
要被增强的对象,一般是业务逻辑类的对象。比如service
Proxy(代理):
一个类被 AOP 织入增强后,就产生一个结果代理类
Aspect(切面):
表示增强的功能,就是一些代码完成的某个功能,非业务功能。是切入点和通知的结合。比如事务、日志等功能;
Joinpoint(连接点):
所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法(一般是类中的业务方),因为Spring只支持方法类型的连接点。
Pointcut(切入点):
切入点指声明的一个或多个连接点的集合。通过切入点指定一组方法。被标记为 final 的方法是不能作为连接点与切入点的。因为最终的是不能被修改的,不能被增强的
Advice(通知/增强):
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
通知定义了增强代码切入到目标代码的时间点,是目标方法执行之前执行,还是之后执等。通知类型不同,切入时间不同。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
切入点定义切入的位置,通知定义切入的时间
Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而AspectJ 采用编译期织入和类装载期织入 。
3.5.2 AspectJ对AOP的实现
对于 AOP 这种编程思想,很多框架都进行了实现。Spring 就是其中之一,可以完成面向切面编程。AspectJ 也实现了 AOP 的功能,且其实现方式更为简捷而且还支持注解式开发。所以,Spring 又将AspectJ 的对于 AOP 的实现也引入到了自己的框架中。
在 Spring 中使用 AOP 开发时,一般使用 AspectJ 的实现方式
AspectJ 是一个优秀面向切面的框架,它扩展了 Java 语言,提供了强大的切面实现。
(1)AspectJ的通知类型
AspectJ 中常用的通知有5种类型:
1. 前置通知
2. 后置通知
3. 环绕通知
4. 异常通知
5. 最终通知
(2)AspectJ的切入点表达式
AspectJ 定义了专门的表达式用于指定切入点。
表达式的原型如下:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
表达式说明:
modifiers-pattern 访问权限类型
ret-type-pattern 返回值类型
declaring-type-pattern 包名类名
name-pattern(param-pattern) 方法名(参数类型和参数个数)
throws-pattern 抛出异常类型
? 表示可选的部分
以上表达式共 4 个部分:
execution(访问权限 方法返回值 方法声明(参数) 异常类型)
切入点表达式要匹配的对象就是目标方法的方法名。所以,execution 表达式中就是方法的签名。
PS:表达式中黑色文字表示可省略部分,各部分间用空格分开。在其中可以使用以下符号:
(3) 示例:
execution(* com.kkb.service.*.*(..))
指定切入点为:定义在 service 包里的任意类的任意方法。
execution(* com.kkb.service..*.*(..))
指定切入点为:定义在 service 包或者子包里的任意类的任意方法。“..”出现在类名中时,后面必须跟 “*”,表示包、子包下的所有类。
execution(* com.kkb.service.IUserService+.*(..))
指定切入点为:IUserService 若为接口,则为接口中的任意方法及其所有实现类中的任意方法;若为类,则为该类及其子类中的任意方法。
3.5.3 注解方式实现AOP
开发阶段:关注核心业务和AOP代码
运行阶段:spring框架会在运行的时候将核心业务和AOP代码通过动态代理的方式编织在一起。
代理方式的选择:是否实现了接口:有接口就选择JDK动态代理;没有就选择CGLIB动态代理。
示例:
1. 创建项目引入依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
2. 创建spring配置文件引入约束
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--在bean标签中 引入AOP约束-->
3. 创建核心业务
核心业务接口:
public interface IService {
void add(int id,String name);
boolean update(int num);
}
核心业务类:
/**
* 核心业务类
*/
public class TeamService implements IService{
@Override
public void add(int id, String name) {
//int num=10/0;
System.out.println("TeamService---- add----");
}
@Override
public boolean update(int num) {
System.out.println("TeamService---- update----");
if(num>666){
return true;
}
return false;
}
}
4. 定义切面类:
package com.kkb.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 切面类
*/
@Component //切面对象的创建权限依然交给spring容器
@Aspect //aspectj 框架的注解 标识是一个切面类
public class MyAspect {
/**
* 当较多的通知增强方法使用相同的 execution 切入点表达式时,编写、维护均较为麻烦。
* AspectJ 提供了@Pointcut 注解,用于定义 execution 切入点表达式。
* 其用法是,将@Pointcut 注解在一个方法之上,以后所有的 execution 的 value 属性值均
* 可使用该方法名作为切入点。代表的就是@Pointcut 定义的切入点。
* 这个使用@Pointcut 注解方法一般使用 private 的标识方法,即没有实际作用的方法。
*/
@Pointcut("execution(* com.kkb.service..*.*(..))")
private void pointCut(){
}
@Before("pointCut()")
public void before(JoinPoint jp){
System.out.println("前置通知:在方法执行之前被调用的通知");
String name = jp.getSignature().getName();
System.out.println("拦截的方法名称:"+name);
Object[] args = jp.getArgs();
System.out.println("方法的参数个数:"+args.length);
System.out.println("方法参数列表:");
for (Object arg : args) {
System.out.println("\t"+arg);
}
}
/**
* AfterReturning 注解声明后置通知
* returning 属性表示返回的结果 如果需要的话可以在后置通知的方法中修改
*/
@AfterReturning(value = "execution(* com.kkb.service..*.update*(..))",returning = "result")
public Object afterReturn(Object result){
if(result!=null){
boolean res = (boolean) result;
if(res){
result=false;
}
}
System.out.println("后置通知:在方法执行之后被调用的通知,result="+result);
return result;
}
/**
* Around 注解声明环绕通知
* ProceedingJoinPoint 中的proceed方法表示目标方法被执行
*/
@Around(value = "execution(* com.kkb.service..*.add*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕方法---目标方法执行之前");
Object proceed = pjp.proceed();
System.out.println("环绕方法---目标方法执行之后");
return proceed;
}
/**
* AfterThrowing 注解声明异常通知方法
* value: 表示切入点表达式
* @param jp
* @param ex
*/
@AfterThrowing(value = "execution(* com.kkb.service..*.*(..))",throwing = "ex")
public void exception(JoinPoint jp,Throwable ex){
//一般会把异常发生的时间,位置,都记录下来
System.out.println("异常通知:在目标方法执行出现异常的时候才会出现的通知,否则不执行");
System.out.println(jp.getSignature()+"方法出现异常,异常信息是:"+ex.getMessage());
}
@After("execution(* com.kkb.service..*.add*(..))")
public void myFinally(){
System.out.println("最终通知:无论是否出现异常都是最后被调用的通知");
}
}
5. 业务类和切面类添加注解:
在定义好切面 Aspect 后,需要通知 Spring 容器,让容器生成“目标类+ 切面”的代理对象。这个代理是由容器自动生成的。只需要在 Spring 配置文件中注册一个基于 aspectj 的自动代理生成器,其就会自动扫描到@Aspect 注解,并按通知类型与切入点,将其织入,并生成代理。
6. spring.xml配置文件中开启包扫描和 注册aspectj的自动代理
<!--包扫描-->
<context:component-scan base-package="com.kkb.service,com.kkb.aop"/>
<!--开启注解AOP的使用-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--aop:aspectj-autoproxy的底层是由 AnnotationAwareAspectJAutoProxyCreator 实现的,
是基于 AspectJ 的注解适配自动代理生成器。
其工作原理是,aop:aspectj-autoproxy通过扫描找到@Aspect 定义的切面类,再由切面类根据切入点找
到目标类的目标方法,再由通知类型找到切入的时间点。-->
切面类分步剖析:
(1)@Before 注解声明前置通知
通过连接点JoinPoint,获得拦截到的方法名称及参数列表
编写测试方法:
package com.kkb.test;
import com.kkb.service.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
TeamService teamService = (TeamService) ac.getBean("teamService");
teamService.add(1001,"湖人");
System.out.println("------------------------------------------");
boolean update = teamService.update(888);
System.out.println("update 结果="+update);
}
}
@Before 注解单独测试结果 :
(2) @AfterReturning 注解声明后置通知
@AfterReturning在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
使用如上测试方法
@AfterReturning注解 单独测试结果为:
(3)@Around 注解声明环绕通知
使用如上测试方法:
@Around注解 单独测试结果为:
(4)@AfterThrowing 注解声明异常通知方法
使用如上测试方法
当核心业务类中add方法int num=10/0 放开时会出现异常,测试一下:
(5)@After注解 声明最终通知方法
使用如上方法测试
@After注解 单独测试结果为:
3.5.4 XML方式实现AOP
将如上注解实现的功能转移到XML中进行配置
1,将切面类中关于AspectJ的AOP注解全部删除(保留@AspectJ注解),其中的方法保留参数
新建一个切面类 叫MyAOP:
package com.kkb.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 切面类
*/
@Component //切面对象的创建权限依然交给spring容器
@Aspect //aspectj 框架的注解 标识是一个切面类
public class MyAOP {
public void before(JoinPoint jp){
System.out.println("MyAOP前置通知:在方法执行之前被调用的通知");
}
public void afterReturn(Object result){
System.out.println("MyAOP后置通知:在方法执行之后被调用的通知,result="+result);
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("MyAOP环绕方法---目标方法执行之前");
Object proceed = pjp.proceed();
System.out.println("MyAOP环绕方法---目标方法执行之后");
return proceed;
}
public void exception(JoinPoint jp,Throwable ex){
//一般会把异常发生的时间,位置,都记录下来
System.out.println("异常通知:在目标方法执行出现异常的时候才会出现的通知,否则不执行");
System.out.println(jp.getSignature()+"方法出现异常,异常信息是:"+ex.getMessage());
}
public void myFinally(){
System.out.println("MyAOP最终通知:无论是否出现异常都是最后被调用的通知");
}
}
2,在spring配置文件中引入aop相关配置
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--在bean标签中 引入AOP约束-->
<context:component-scan base-package="com.kkb.service,com.kkb.aop"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--xml方式实现aop-->
<aop:config>
<!--声明切入点的表达式,可以声明多个-->
<aop:pointcut id="pt1" expression="execution(* com.kkb.service..*.*(..))"/>
<aop:pointcut id="pt2" expression="execution(* com.kkb.service..*.add*(..))"/>
<aop:aspect ref="myAOP">
<!--此处引用的的myAOP为类名首字母小写-->
<aop:before method="before" pointcut="execution(* com.kkb.service..*.*(..))"></aop:before>
<aop:after-returning method="afterReturn" pointcut-ref="pt1" returning="result"></aop:after-returning>
<aop:after-throwing method="exception" pointcut-ref="pt1" throwing="ex"></aop:after-throwing>
<aop:after method="myFinally" pointcut-ref="pt1"></aop:after>
<aop:around method="around" pointcut-ref="pt2"></aop:around>
</aop:aspect>
</aop:config>
</beans>
测试使用如上相同的方法
测试结果为:
后续博主会补齐Spring的其它内容,如果以上内容残缺或错误,可以私信博主或在评论区留言
希望看到这里的朋友能够使您对于XML和JSON的理解更上一层楼,如果这篇文章对您有所帮助,希望请您不要吝啬您勤快的小手 ,为博主点个赞关注一下,博主会在今后会发布其它文章,谢谢观看!!!