一、bean生命周期-后处理bean(Bean后处理器)
1、编写一个类实现接口BeanPostProcessor 实现接口中的两个方法
public class LifeCycle implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之前。。。。。。。"+beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之后。。。。。。。"+beanName);
return bean;
}
}
2、在applicationContext.xml中配置这个Bean
(可以不用配置id,因为这个Bean是由spring容器来自动调用,只要在容器中有新的Bean对象初始化出来,bean后处理器都要执行)
<!--配置后处理器-->
<bean class="com.yunhe.lifeCycle.LifeCycle"></bean>
此时这个Bean将作用于当前spring中所有的其它Bean.(初始化前,初始化加入功能增强)
二、依赖注入bean属性(手动注入)
依赖注入三种方式
-
setter方法(默认)
<bean id="user" class="com.yunhe.entity.User" init-method="init" destroy-method="destory"> <!--property:类中属性 name:属性名 value:值--> <property name="username" value="jack"></property> <property name="age" value="20"></property> <!--ref:引用spring容器中bean实例 实例的id名--> <property name="phone" ref="phone"></property> </bean> <bean id="phone" class="com.yunhe.entity.Phone"> <property name="brand" value="苹果"></property> <property name="price" value="5000"></property> </bean>
-
有参构造方法
<bean id="user6" class="com.yunhe.bean.User"> <constructor-arg index="0" type="java.lang.String" value="大黄"></constructor-arg> <constructor-arg index="1" type="int" value="18"></constructor-arg> <constructor-arg index="2" type="com.yunhe.bean.Computer" ref="computer"></constructor-arg> </bean>
-
p命名空间方式
P命名空间注入本质也是set方法注入,但比起上述的set方法注入更加方便,主要体现在配置文件中,如下:
首先,需要引入P命名空间:
xmlns:p="http://www.springframework.org/schema/p"
需要修改注入方式
<bean id="user7" class="com.yunhe.bean.User" p:username="小白" p:age="20" p:computer-ref="computer"></bean>
引入其他配置文件(分模块开发)
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,而在Spring主配置文件通过import标签进行加载
<import resource="applicationContext-xxx.xml"/>
SpringEl
#{}:引用其他bean实例
#{T(java.lang.Math).PI}:引用静态资源
执行对象的方法: #{对象名.方法名()}
集合注值
创建类
public class MyCollection {
private List<String> names;
private Set<Integer> ages;
private Map<User ,Integer> persons;
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public Set<Integer> getAges() {
return ages;
}
public void setAges(Set<Integer> ages) {
this.ages = ages;
}
public Map<User, Integer> getPersons() {
return persons;
}
public void setPersons(Map<User, Integer> persons) {
this.persons = persons;
}
@Override
public String toString() {
return "MyCollection{" +
"names=" + names +
", ages=" + ages +
", persons=" + persons +
'}';
}
}
配置applicationContext.xml
<!--集合注入值-->
<bean id="myCollection" class="com.yunhe.bean.MyCollection">
<property name="names">
<list>
<value>张三</value>
<value>李四</value>
<value>王五</value>
</list>
</property>
<property name="ages">
<set>
<value>18</value>
<value>19</value>
<value>20</value>
</set>
</property>
<property name="persons">
<map>
<entry key-ref="user4" value="888"></entry>
<entry key-ref="user5" value="999"></entry>
<entry key-ref="user6" value="666"></entry>
</map>
</property>
三、装配Bean基于注解
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
常见开发使用方式:注解 + xml配置
Spring原始注解主要是替代的配置
注解 | 说明 |
---|---|
@Component | 使用在类上用于实例化Bean |
@Controller | 使用在web层类上用于实例化Bean |
@Service | 使用在service层类上用于实例化Bean |
@Repository | 使用在dao层类上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifier,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法是Bean的初始化方法 |
@PreDestroy | 使用在方法上标注该方法是Bean的销毁方法 |
注意:
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
<!--注解的组件扫描-->
<context:component-scan base-package="com.itheima"></context:component-scan>
使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化。
组件注解
@Repository 、 @Service 、 @Controller 都是 @Component 的子类,具有Component所有功能
这三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强
自动注入注解
@AutoWired 将自动注入,默认将按照类型注入
如果需要使用按照名称注入,需要添加@Qualifier(“bean名称”)
扩展:@Resource 与 @AutoWired等效,但Resource可以自己设置bean名称
@Service
public class IUserServiceImpl implements IUserService {
// @Autowired
// @Qualifier("oracleDao")
@Resource(name="oracleDao")
private IUserDao iUserDao;
生命周期注解
@PostConstruct 用于配置初始化
@PreDestroy 用于配置销毁
@Service
public class IUserServiceImpl implements IUserService {
@PostConstruct
public void init(){
System.out.println("init++++++++++++++");
}
@PreDestroy
public void destory(){
System.out.println("destory-------------------");
}}
作用于注解
单例:@Scope(“singleton”)
多例:@Scope(“prototype”)
//@Scope("singleton")
@Scope("prototype")
public class IUserServiceImpl implements IUserService {
//此处省略代码
}
四、 Spring整合Junit
①导入spring集成Junit的坐标
②使用@Runwith注解替换原来的运行期
③使用@ContextConfiguration指定配置文件或配置类
④使用@Autowired注入需要测试的对象
⑤创建测试方法进行测试
<!--注意 spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IUserDaoService iUserDaoService;
@Test
public void test(){
iUserDaoService.addUser();
}
}
五、Spring 的 AOP 简介
5.1 什么是 AOP
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
5.2 AOP 的作用及其优势
作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,并且便于维护
5.3 AOP 的底层实现
实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
5.4 AOP 的动态代理技术
常用的动态代理技术
JDK 代理 : 基于接口的动态代理技术
cglib 代理:基于父类的动态代理技术
5.5 AOP 相关概念
Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
在正式讲解 AOP 的操作之前,我们必须理解 AOP 的相关术语,常用的术语如下:
-
Target(目标对象):代理的目标对象
-
Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
-
Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
-
Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
-
Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
-
Aspect(切面):是切入点和通知(引介)的结合
-
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
-
aop:面向切面编程
-
aop底层实现:基于JDK的动态代理 和 基于Cglib的动态代理
-
aop的重点概念:
Pointcut(切入点):被增强的方法
Advice(通知/ 增强):封装增强业务逻辑的方法
Aspect(切面):切点+通知
Weaving(织入):将切点与通知结合的过程
开发明确事项:
谁是切点(切点表达式配置)
谁是通知(切面类中的增强方法)
将切点和通知进行织入配置
六、 基于 XML 的 AOP 开发
6.1 快速入门
①导入 AOP 相关坐标
②创建目标接口和目标类(内部有切点)
③创建切面类(内部有增强方法)
④将目标类和切面类的对象创建权交给 spring
⑤在 applicationContext.xml 中配置织入关系
⑥测试代码
①导入 AOP 相关坐标
<!--导入spring的context坐标,context依赖aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- aspectj的织入 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
②创建目标接口和目标类(内部有切点)
public interface IUserDaoService {
public void addUser();
public void deleteUserById();
public void updateUserById();
public void queryUserById();
}
public class IUserDaoServiceImpl implements IUserDaoService {
@Override
public void addUser() {
// int i=9/0;
System.out.println("新增用户");
}
@Override
public void deleteUserById() {
System.out.println("删除用户");
}
@Override
public void updateUserById() {
System.out.println("更新用户");
}
@Override
public void queryUserById() {
System.out.println("查找用户");
}
}
③创建切面类(内部有增强方法)
public class Inform {
/*
前置通知
目标方法执行之前调用
后置通知(目标方法如果发生异常,不调用)
在目标方法执行之后调用
环绕通知
在目标方法之前和之后调用
异常拦截通知
如果目标方法发生异常,调用
后置通知(无论目标方法是否发生异常,都会调用)
在目标方法执行之后,调用
*/
public void before(){
System.out.println("前置通知");
}
public void afterReturning(){
System.out.println("后置通知(目标方法如果发生异常,不调用)");
}
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知 欢迎光临");
Object proceed = joinPoint.proceed();
System.out.println("环绕通知 谢谢惠顾");
return proceed;
}
public void afterException(){
System.out.println("异常通知");
}
public void after(){
System.out.println("我是后置通知(不管异常是否发生,都会执行。。)");
}
}
④将目标类和切面类的对象创建权交给 spring
<!-- 目标对象-->
<bean id="iuserDaoService" class="com.yunhe.service.impl.IUserDaoServiceImpl"></bean>
<!-- 通知对象-->
<bean id="inform" class="com.yunhe.inform.Inform"></bean>
⑤在 applicationContext.xml 中配置织入关系
导入aop命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
⑤在 applicationContext.xml 中配置织入关系
配置切点表达式和前置增强的织入关系
<!-- aop配置-->
<aop:config>
<!-- 全路径测试
public void com.yunhe.service.impl.IUserDaoServiceImpl.addUser();
* com.yunhe.service..*ServiceImpl.*(..)
-->
<!-- 配置切入点-->
<aop:pointcut id="pc" expression="execution(* com.yunhe.service..*ServiceImpl.*(..))"/>
<!-- 配置切面 ref:指定通知类-->
<aop:aspect ref="inform">
<aop:before method="before" pointcut-ref="pc" ></aop:before>
<aop:after-returning method="afterReturning" pointcut-ref="pc"></aop:after-returning>
<aop:after-throwing method="afterException" pointcut-ref="pc"></aop:after-throwing>
<aop:after method="after" pointcut-ref="pc"></aop:after>
<aop:around method="around" pointcut-ref="pc" ></aop:around>
</aop:aspect>
</aop:config>
⑥测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IUserDaoService iUserDaoService;
@Test
public void test(){
iUserDaoService.addUser();
}
}
⑦测试结果
6.2XML 配置 AOP 详解
1) 切点表达式的写法
表达式语法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
-
访问修饰符可以省略
-
返回值类型、包名、类名、方法名可以使用星号* 代表任意
-
包名与类名之间一个点 . 代表当前包下的类,两个点 … 表示当前包及其子包下的类
-
参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表
例如:
execution(public void com.itheima.aop.Target.method())
execution(void com.itheima.aop.Target.*(..))
execution(* com.itheima.aop.*.*(..))
execution(* com.itheima.aop..*.*(..))
execution(* *..*.*(..))
2) 通知的类型
通知的配置语法:
<aop:通知类型 method=“切面类中方法名” pointcut=“切点表达式"></aop:通知类型>
3) 切点表达式的抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式。
<aop:config>
<!--引用myAspect的Bean为切面对象-->
<aop:aspect ref="myAspect">
<aop:pointcut id="myPointcut" expression="execution(* com.itheima.aop.*.*(..))"/>
<aop:before method="before" pointcut-ref="myPointcut"></aop:before>
</aop:aspect>
</aop:config>
2.3 知识要点
- aop织入的配置
<aop:config>
<aop:aspect ref=“切面类”>
<aop:before method=“通知方法名称” pointcut=“切点表达式"></aop:before>
</aop:aspect>
</aop:config>
- 通知的类型:前置通知、后置通知、环绕通知、异常抛出通知、最终通知
- 切点表达式的写法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
3.基于注解的 AOP 开发
开闭原则(OCP,Open Close Principle)
遵循开闭原则设计出的模块具有两个主要特征:
(1)对于扩展是开放的(Open for extension)。这意味着模块的行为是可以扩展的。当应用的需求改变时,我们可以对模块进行扩展,使其具有满足那些改变的新行为。也就是说,我们可以改变模块的功能。
(2)对于修改是关闭的(Closed for modification)。对模块行为进行扩展时,不必改动模块的源代码或者二进制代码。模块的二进制可执行版本,无论是可链接的库、DLL或者.EXE文件,都无需改动。