2019独角兽企业重金招聘Python工程师标准>>>
第二种实现方式——自定义实现
通过springAPI来实现需要通过实现接口或者继承来构建关注点。自定义实现的话就不需要了。Log代码如下
public class Log {
public void before(){
System.out.println("——————方法执行前");
}
public void after(){
System.out.println("——————方法执行后");
}
}
Service和ServiceImpl代码不变。
public interface Service {
public void add();
public void update();
public void delete();
public void search();
}
public class ServiceImpl implements Service{
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void update() {
System.out.println("修改用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void search() {
System.out.println("查询用户");
}
}
beans配置修改如下。在aop:config里增加aop:aspect,ref是关联的关注点。aop:pointcut同样是切入点。befor和after对应前置通知和后置通知。
<?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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="service" class="ServiceImpl"/>
<bean id="log" class="Log"/>
<aop:config>
<aop:aspect ref="log">
<aop:pointcut id="pointcut" expression="execution(* ServiceImpl.*(. .))"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
测试如下