一、注解实现切面
项目结构
接口
/** 用户数据访问层接口 */
public interface UserDao {
void ins();
void del();
void upd();
void sel();
}
实现类
public class UserDaoImpl implements UserDao {
@Override
public void ins() {
System.out.println("insert命令");
}
@Override
public void del() {
System.out.println("delete命令");
}
@Override
public void upd() {
System.out.println("update命令");
}
@Override
public void sel() {
System.out.println("select命令");
}
}
使用注解自定义切面
@Aspect
public class AnnoPointCut {
@Before("execution(* com.shengjava.aop.dao.impl.UserDaoImpl.*(..))")
public void before() {
System.out.println("----- before -----");
}
@After("execution(* com.shengjava.aop.dao.impl.UserDaoImpl.*(..))")
public void after () {
System.out.println("----- after -----");
}
/** 在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点 */
@Around("execution(* com.shengjava.aop.dao.impl.UserDaoImpl.*(..))")
public void around (ProceedingJoinPoint jp) throws Throwable {
System.out.println("----- around before -----");
// 执行(该类还可以获取到一些类的其他信息)
jp.proceed();
System.out.println("----- around 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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="userDaoImpl" class="com.shengjava.aop.dao.impl.UserDaoImpl"/>
<bean id="myPointCut" class="com.shengjava.aop.log.AnnoPointCut"/>
<!-- 方式三:使用注解(请看AnnoPointCut类中的注解) -->
<!-- 开启注解支持 (属性proxy-target-class值:默认"false"使用JDK动态代理,"true"使用cglib动态代理)-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
测试类
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 动态代理(代理的是接口,所以类型应该也是接口类型)
UserDao ud = context.getBean("userDaoImpl", UserDao.class);
// 执行
ud.ins();
}
}
输出
----- around before -----
----- before -----
insert命令
----- around after -----
----- after -----
扩展
aop设置开启注解支持时,可以设置属性proxy-target-class值:默认"false"使用JDK动态代理),"true"使用cglib动态代理)–>
<aop:aspectj-autoproxy proxy-target-class="true"/>
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录