上篇文章记录Spring中使用动态代理,切面我们是 重写了 AfterReturningAdvice 接口和MethodBeforeAdvice 接口中的方法,下边记录自定义切面,我们自定义的切面不能控制目标类、方法,局限性很大:
定义自定义切面 - diyPoint
package com.lxc.diy;
public class diyPoint {
public void beforeLog() {
System.out.println("前置切面");
}
public void afterLog() {
System.out.println("后置切面");
}
}
定义接口 - UserService
package com.lxc.service;
public interface UserService {
public void query();
public void delete();
public void edit();
public void add();
}
重写接口类 - UserServiceImp
package com.lxc.service;
public class UserServiceImp implements UserService{
@Override
public void query() {
System.out.println("query");
}
@Override
public void delete() {
System.out.println("delete");
}
@Override
public void edit() {
System.out.println("edit");
}
@Override
public void add() {
System.out.println("add");
}
}
beans.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--定义bean-->
<bean id="diyPoint" class="com.lxc.diy.diyPoint"/>
<bean id="imp" class="com.lxc.service.UserServiceImp"/>
<aop:config>
<!-- <aop:aspect /> 引用上边的 自定义切面,
ref:要引用的类 -->
<aop:aspect ref="diyPoint">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.lxc.service.UserServiceImp.*(..))" />
<!--通知什么时间执行-->
<aop:before method="beforeLog" pointcut-ref="point" />
<aop:after method="afterLog" pointcut-ref="point" />
</aop:aspect>
</aop:config>
</beans>
测试:
import com.lxc.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = ctx.getBean("imp", UserService.class);
userService.add();
}
}
输出如下: