使用AOP注解配置
1.导入jiar包
2.配置xml文件
beans添加xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation中添加http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.login"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
扫描项目实现注入或者织入
<context:component-scan base-package="com.login"></context:component-scan>
通过配置织入@Aspectj切面
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
AOP注解使用
织入点语法,普便用法:
execution(public * com.login.dao..*.*(..))
1.@Aspect :切面,放在需要动态代理类上
2. @Before :在被代理对象执行方法前执行。
3. @AfterThrowing:被代理对象获取异常时执行的方法
4. @Around:可以在被代理对象前后添加方法。
@Aspect
@Component
public class LogInterceptor {
@Before("execution(public * com.login.dao..*.*(..))")
public void beforeMethod(){
System.out.println("save before...");
}
@AfterThrowing("execution(public * com.login.dao.*.*(..))")
public void afterThrow(){
System.out.println("found exception..");
}
@Around("execution(public * com.login.dao.*.*(..))")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("save start...");
pjp.proceed();
System.out.println("save end...");
}
@AfterReturning("execution(public * com.login.dao.*.*(..))")
public void afterMethod(){
System.out.println("save afterRetrunning...");
}