听说坚持一件事后果很严重,鄙人不信邪,表示要试试。😃 此博文仅为学习笔记,每天记录。防止错误观念传播,萌新谨慎观看 :)
Aop的实现:aop是个标准,是一个规范。
Aop的实现框架
1、spring中的事务使用APO(实际开发中使用较少)
2、Aspectj:开源的Aop框架,Spring已经继承AspectJ
AspectJ完成Aop的两种方式
1、XML配置文件:配置全局事务
2、注解实现
学习AspectJ的使用:
1、切面的执行时间,在规范中叫Advice(通知、增强),对应的注解有
前置通知 before
后置通知 after_returning
异常通知 after_throwing
最终通知 after
环绕通知 aop:around
2、表示切面执行位置,切入点表达式 execution(访问权限(可省略) 方法返回值 方法声明(可省略) 异常类型) execution(public * * (..))
例如:execution(* set*(..)) //表示任何以set开始的方法、
execution(*,com.ziweiwang.xxx.*.*(..)) //表示在 com.ziweiwang.xxx包下的任意类的任意方法
使用AspectJ标准实现Aop:
使用Aop:给已经存在目标类增加额外的功能,且是在不改变原有代码的情况下。
使用AspectJ实现Aop的基本步骤
1.开始新建一个maven项目
2、加入对应的依赖:spring依赖、AspectJ依赖、
3、创建目标类,接口和他的实现类,给类方法增强功能
4、创建切面类
1、在类上加@AspectJ
2、在类中定义方法,方法就是切面要执行的代码,在方法上加入aspectj的注解。例如:@before,切入点表达式 execution()
5、创建spring的配置文件,声明对象并把对象统一放入容器之中。声明对象可以用注解或XML配置文件方式。
1、声明目标对象
2、声明切面对象
3、声明Aspectj框架中的自动代理生成器标签,自动代理生成器自动创建代理对象。
代码示例(初始版):
//目标接口
public interface StudentService {
void doHomeWork();
void doSomeThint();
}
//目标接口实现类
public class StudentServiceImpl implements StudentService{
@Override
public void doHomeWork() {
System.out.println("doHomeWork");
}
@Override
public void doSomeThint() {
System.out.println("doSomeThint");
}
}
//切面类
@Aspect
public class StudentTools {
@Before(value = "execution(public void testProxy.StudentServiceImpl.doHomeWork(..))")
public void doLog() {
System.out.println("log");
}
@After(value = "execution(public void testProxy.StudentServiceImpl.doSomeThint(..))")
public void doDate() {
System.out.println("doDate"+new Data());
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean id='ServiceImpl' class="testProxy.StudentServiceImpl" />
<bean id='ServiceTools' class="testProxy.StudentTools" />
<aop:aspectj-autoproxy />
</beans>
测试类
public class TProxy {
public static void main(String[] args) {
String configString="proxy.xml";
ApplicationContext cn=new ClassPathXmlApplicationContext(configString);
// String[] strings=cn.getBeanDefinitionNames();
// System.out.println(strings[0]);
// //从容器中获取目标对象
StudentService proixy=(StudentService)cn.getBean("ServiceImpl");
proixy.doHomeWork();
}
}
END 未完待续。。