1.AOP简介
a.AOP通过提供另外一种思考程序结构的途经来弥补面向对象编程(OOP)的不足。在OOP中模块化的关键单元是类(classes),而在AOP中模块化的单元则是切面。切面能对关注点进行模块化,例如横切多个类型和对象的事务管理。(在AOP术语中通常称作横切(crosscutting)关注点。)
b.AOP框架是Spring的一个重要组成部分。但是Spring IoC容器并不依赖于AOP,这意味着你有权利选择是否使用AOP,AOP做为Spring IoC容器的一个补充,使它成为一个强大的中间件解决方案。
c.AOP(aspect oriented programming)面向切面编程:在不改变原来代码的情况下,增加新的功能。通过代理方式,横向编程。
传统的编程方式:自上而下纵向编程。(JSP-Action-Service-DAO)
2.名词解释
a.切面(Aspect):一个关注点的模块化,这个关注点可能会横切多个对象。事务管理是J2EE应用中一个关于横切关注点的很好的例子
b.连接点(Joinpoint):在程序执行过程中某个特定的点,比如某方法调用的时候或者处理异常的时候。在Spring AOP中,一个连接点总是表示一个方法的执行。
c.通知(Advice):在切面的某个特定的连接点上执行的动作。其中包括了“around”、“before”和“after”等不同类型的通知(通知的类型将在后面部分进行讨论)。许多AOP框架(包括Spring)都是以拦截器做通知模型,并维护一个以连接点为中心的拦截器链。
d.切入点(Pointcut):匹配连接点的断言。通知和一个切入点表达式关联,并在满足这个切入点的连接点上运行(例如,当执行某个特定名称的方法时)。切入点表达式如何和连接点匹配是AOP的核心:Spring缺省使用AspectJ切入点语法。
e.引入(Introduction):用来给一个类型声明额外的方法或属性(也被称为连接类型声明(inter-type declaration))。Spring允许引入新的接口(以及一个对应的实现)到任何被代理的对象。例如,你可以使用引入来使一个bean实现IsModified接口,以便简化缓存机制。
f.目标对象(Target Object): 被一个或者多个切面所通知的对象。也被称做被通知(advised)对象。 既然Spring AOP是通过运行时代理实现的,这个对象永远是一个被代理(proxied)对象。
g.AOP代理(AOP Proxy):AOP框架创建的对象,用来实现切面契约(例如通知方法执行等等)。在Spring中,AOP代理可以是JDK动态代理或者CGLIB代理。
h.织入(Weaving):把切面连接到其它的应用程序类型或者对象上,并创建一个被通知的对象。这些可以在编译时(例如使用AspectJ编译器),类加载时和运行时完成。Spring和其他纯Java AOP框架一样,在运行时完成织入。
3.AOP在spring中的作用
a.提供声明式服务(声明式事务);b.允许用户实现自定义切面
4.Spring实现AOP
a.通过Spring API实现。
1.log4j.properties
log4j.rootLogger = debug , stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2.com.shi.config.applicationContext.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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- spring容器扫描指定包下的所有类,如果类上有注解,那么根据注解产生相应bean对象以及映射信息 -->
<context:component-scan base-package="com.shi"/>
<aop:config>
<aop:pointcut expression="execution(* com.shi.service.impl.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
3.com.shi.dto.ResultDTO.java com.shi.dto.UserDTO.java
package com.shi.dto;
/**
* dto
* @author shixiangcheng
* 2019-05-13
*/
public class UserDTO {
private int id;
private String name="";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[id="+id+",name="+name+"]";
}
}
package com.shi.dto;
/**
* dto
* @author shixiangcheng
* 2019-05-13
*/
public class ResultDTO {
private String msg="";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "[msg="+msg+"]";
}
}
4.com.shi.log.AfterLog.java com.shi.log.BeforeLog.java
package com.shi.log;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.stereotype.Component;
/**
* 后置通知(切面)
* @author shixiangcheng
* 2019-05-13
*/
@Component
public class AfterLog implements AfterReturningAdvice{
private Logger logger=Logger.getLogger(this.getClass());
/**
* 目标方法执行后执行的通知
* returnValue:返回值;method:被调用的方法对象;args:被调用的方法对象的参数;
* target:被调用的方法对象的目标对象
*/
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
logger.info("后置通知:"+target.getClass().getName()+"的"+method.getName()+"方法被执行,参数"+args[0].toString()+"返回值"+returnValue);
}
}
package com.shi.log;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;
/**
* 前置通知(切面)
* @author shixiangcheng
* 2019-05-13
*/
@Component
public class BeforeLog implements MethodBeforeAdvice{
private Logger logger=Logger.getLogger(this.getClass());
/**
* @param method 被调用方法对象
* @param args 被调用的方法的参数
* @param target 被调用的方法的目标对象
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
logger.info("前置通知:"+target.getClass().getName()+"的"+method.getName()+"方法被执行,参数:"+args[0].toString());
}
}
5.com.shi.service.UserService.java
package com.shi.service;
import com.shi.dto.ResultDTO;
import com.shi.dto.UserDTO;
/**
* 接口
* @author shixiangcheng
* 2019-05-13
*/
public interface UserService {
public ResultDTO add(UserDTO userDTO);
}
6.com.shi.service.UserServiceImpl.java
package com.shi.service.impl;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.shi.dto.ResultDTO;
import com.shi.dto.UserDTO;
import com.shi.service.UserService;
/**
* 实现类
* @author shixiangcheng
* 2019-05-13
*/
@Service("userService")
public class UserServiceImpl implements UserService {
private Logger logger=Logger.getLogger(this.getClass());
@Override
public ResultDTO add(UserDTO userDTO) {
logger.info("add==="+userDTO.toString());
ResultDTO resultDTO=new ResultDTO();
resultDTO.setMsg("SUCCESS!");
return resultDTO;
}
}
7.测试类com.shi.test.Test.java
package com.shi.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.shi.dto.UserDTO;
import com.shi.service.UserService;
/**
* 测试类
* @author shixiangcheng
* 2019-05-13
*/
public class Test {
public static void main(String [] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:com/shi/config/applicationContext.xml");
UserService userService=(UserService)applicationContext.getBean("userService");
UserDTO userDTO=new UserDTO();
userDTO.setId(1);
userDTO.setName("程序员");
Object resultDTO=userService.add(userDTO);
}
}
8.执行测试类
DEBUG [main] - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties]
DEBUG [main] - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment]
DEBUG [main] - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source. Returning [null]
DEBUG [main] - Returning cached instance of singleton bean 'userService'
INFO [main] - 前置通知:com.shi.service.impl.UserServiceImpl的add方法被执行,参数:[id=1,name=程序员]
INFO [main] - add===[id=1,name=程序员]
INFO [main] - 后置通知:com.shi.service.impl.UserServiceImpl的add方法被执行,参数[id=1,name=程序员]返回值[msg=SUCCESS!]
b.自定义类来实现。
1.com.shi.log.Log.java
package com.shi.log;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* 日志
* @author shixiangcheng
* 2019-05-13
*/
@Aspect
@Component
public class Log {
private Logger logger=Logger.getLogger(this.getClass());
public void before(){
logger.info("--执行前--");
}
public void after(){
logger.info("--执行后--");
}
public void aroud(ProceedingJoinPoint jp) throws Throwable{
logger.info("--环绕前--");
logger.info("--方法签名:"+jp.getSignature());
logger.info("--参数:"+jp.getArgs()[0].toString());
Object obj=jp.proceed();//执行目标方法
logger.info("--环绕后--返回值:"+obj.toString());
}
}
2.配置文件applicationContext.xml变更
<aop:config>
<aop:aspect ref="log">
<aop:pointcut expression="execution(* com.shi.service.impl.*.*(..))" id="pointcut"/>
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<aop:after method="after" pointcut-ref="pointcut"></aop:after>
<aop:around method="aroud" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
3.其它文件不变,执行测试类
DEBUG [main] - Returning cached instance of singleton bean 'userService'
DEBUG [main] - Returning cached instance of singleton bean 'log'
INFO [main] - --执行前--
DEBUG [main] - Returning cached instance of singleton bean 'log'
INFO [main] - --环绕前--
INFO [main] - --方法签名:ResultDTO com.shi.service.UserService.add(UserDTO)
INFO [main] - --参数:[id=1,name=程序员]
INFO [main] - add===[id=1,name=程序员]
INFO [main] - --环绕后--返回值:[msg=SUCCESS!]
DEBUG [main] - Returning cached instance of singleton bean 'log'
INFO [main] - --执行后--
c.通过注解实现。
1.com.shi.log.Log.java
package com.shi.log;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* 日志
* @author shixiangcheng
* 2019-05-13
*/
@Aspect
@Component
public class Log {
private Logger logger=Logger.getLogger(this.getClass());
@Before("execution(* com.shi.service.impl.*.*(..))")
public void before(){
logger.info("--执行前--");
}
@After("execution(* com.shi.service.impl.*.*(..))")
public void after(){
logger.info("--执行后--");
}
@Around("execution(* com.shi.service.impl.*.*(..))")
public void aroud(ProceedingJoinPoint jp) throws Throwable{
logger.info("--环绕前--");
logger.info("--方法签名:"+jp.getSignature());
logger.info("--参数:"+jp.getArgs()[0].toString());
Object obj=jp.proceed();//执行目标方法
logger.info("--环绕后--返回值:"+obj.toString());
}
}
2.配置文件applicationContext.xml变更
<!-- spring容器扫描指定包下的所有类,如果类上有注解,那么根据注解产生相应bean对象以及映射信息 -->
<context:component-scan base-package="com.shi"/>
<aop:aspectj-autoproxy/>
3.其它文件不变,执行测试类。
DEBUG [main] - Returning cached instance of singleton bean 'userService'
DEBUG [main] - Returning cached instance of singleton bean 'log'
INFO [main] - --环绕前--
INFO [main] - --方法签名:ResultDTO com.shi.service.UserService.add(UserDTO)
INFO [main] - --参数:[id=1,name=程序员]
INFO [main] - --执行前--
INFO [main] - add===[id=1,name=程序员]
INFO [main] - --环绕后--返回值:[msg=SUCCESS!]
INFO [main] - --执行后--
5.AOP的优点
使得真实角色处理的业务更加纯粹,不再去关注一些公共的事情。公共的业务由代理来完成。公共业务发生扩展时变得更加集中和方便。
6.AOP的重要性
Spring AOP就是将公共的业务(如日志,安全,缓存,事务,异常处理等)和领域业务结合。当执行领域业务时将会把公共业务加进来。实现公共业务的重复利用。领域业务更加纯粹。程序员专注于领域业务,其本质还是动态代理。