aop:面向切面编程,是对面向对象的一种补充。
通过切面在类中加入事务,日志,权限和i常处理等。现在使用较多的aop编程方法是Aspectj,是一种基于Java语言的aop框架。
aop编程可以做到一次性在你需要做增强方法的方法中做增强。
首先要有一个增强类,实现的是对类的增强的方法,在这里实现的是环绕通知,这里只是测试类,在之后的编程中可以把输出的操作前和操作后换成具体的方法。
package lu.nynu.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogAspect {
Logger logger = LoggerFactory.getLogger(LogAspect.class);
public Object round(ProceedingJoinPoint point) throws Throwable{
System.out.println("操作前");
Object object=point.proceed();//执行当前目标方法
System.out.println("操作后");
return object;
}
}
接下来要定义目标类(需要被增强的类)这里可以实现一个接口,也可以不实现:
package lu.nynu.service;
public class StudentService implements BaseService{
@Override
public void add() {
System.out.println("添加student操作");
}
@Override
public void update() {
System.out.println("修改student操作");
}
}
接下来就是配置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"
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">
<!-- 目标类 -->
<bean id="studentService" class="lu.nynu.service.StudentService"></bean>
<!-- 增强类 -->
<bean id="logAspect" class="lu.nynu.aspect.LogAspect"></bean>
<!-- aop配置 -->
<aop:config proxy-target-class="true">
<!-- <aop:pointcut expression="execution(* lu.nynu.service.*.*(..))" id="myPointCut" />
<aop:advisor advice-ref="logAspect" pointcut-ref="myPointCut" /> -->
<aop:aspect ref="logAspect">
<aop:pointcut expression="execution(* lu.nynu.service.*.*(..))"
id="myPointCut" />
<aop:around method="round" pointcut-ref="myPointCut" />
</aop:aspect>
</aop:config>
</beans>
proxy-target-class属性,默认是false,采用cglib代理方法,要求目标类不能有接口,改成TRUE就可以了
execution(* lu.nynu.service.*.*(..)) 定义切面:
第一个*表示所有返回值
后两个.*表示包路径下的所有类的所有方法
(..)表示所有参数
接下来就是一个测试方法package lu.nynu.test;
import lu.nynu.service.StudentService;
import lu.nynu.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void f1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");//加载配置文件
StudentService studentService= (StudentService) ac.getBean("studentService");
studentService.add();
}
}