什么叫面向切面编程?
就是在编程的时候 将我们的重复的代码抽取出来形成方法 再形成一个类、这个类就是切面类、当我们在执行原来代码的时候 使用代理的设计模式 动态植入我们抽取出来的代码 的这种编程方式就称为 面向切面编程
1、手动实现下面向切面编程(使用CGLIB代理来实现)
1.1 编写业务类
@Component
public class UserService {
/**
* 这是一个add的方法
*/
public void add(){
System.out.println("添加数据完成....");
}
}
1.2 编写aop类
@Component
public class Aop {
public void begin(){
System.out.println("开启事务");
}
public void commit(){
System.out.println("提交事务");
}
}
1.3 编写代理类
@Component
public class UserServiceProxy implements MethodInterceptor {
@Autowired
Aop aop;
/**
* 获取代理类
* @return
*/
public UserService getUserServiceProxy(){
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(UserService.class);
enhancer.setCallback(this);
return (UserService) enhancer.create();
}
/**
* 这里就是方法的拦截
* @param obj
* @param method
* @param args
* @param proxy
* @return
* @throws Throwable
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
aop.begin();
Object invoke = method.invoke(new UserService(), args);
aop.commit();
return invoke;
}
}
1.4 编写配置文件
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd"
>
<context:component-scan base-package="com.qf.cd.aop.sd"></context:component-scan>
</beans>
1.5 编写测试类
public class Test001 {
public static void main(String[] args){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean-aop1.xml");
UserService userServiceProxy = context.getBean(UserServiceProxy.class).getUserServiceProxy();
userServiceProxy.add();
}
}