下面我们来说一下使用注解实现aop编程.我们在前面的例子基础上修改就好了.
1.目标类对象UserServiceImpl.java
首先UserServiceImpl这个类我们要使用注解实现bean的装配,和前面我们说过的一样.只要在类声明的上面@Service注解就可以了
package service.impl;
import org.springframework.stereotype.Service;
import service.UserService;
@Service("userservice")
public class UserServiceImpl implements UserService {
/*
* 这里正常应该是调用dao的方法,这里我们就用输出语句代替了
*/
@Override
public void addUser() {
System.out.println("添加用户");
}
@Override
public void deleteUser() {
System.out.println("删除用户");
}
}
2.增强代码 MyAspect.java
这里要仔细看下面的代码了,和我们以前的有所不同
package aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("myaspect") //除了框架三层以外的,我们都可以用@Component来注解
@Aspect //注意这里要使用@Aspect来注解一下切面
public class MyAspect {
@Before("execution(* service..*(..))")//使用before来注解切入点的前面,括号里面是切入点是哪个
public void before(){
System.out.println("开启事务");
}
@AfterReturning("execution(* service..*(..))")
public void after(){
System.out.println("提交事务");
}
}
3.我们要配置一下配置文件applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="service,aspect"></context:component-scan>
<!-- 这里我们要用下面这个 aop:aspectj-autoproxy标签来自动实现代理,
实际上就是来识别上面注解的@Aspect@Before这些注解的,如果我们不写这个标签,
增强代码是没进行织入的-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
4.测试一下,其实测试类和前面的一样
- 补充1:
- 在MyAspect这个增强代码类中:还可以使用一些其他注解
- @AfterThrowing异常增强
- @After最终增强
- @Around环绕增强(必须手动调用目标方法)
- 在MyAspect这个增强代码类中:还可以使用一些其他注解
- 补充2:
- MyAspect这个类可以有些改进
-
import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component("myaspect") //除了框架三层以外的,我们都可以用@Component来注解 @Aspect //注意这里要使用@Aspect来注解一下切面 public class MyAspect { //配置一个切入点的注解 @Pointcut("execution(* service..*(..))") public void pointcut(){} @Before("pointcut()")//使用before来注解切入点的前面,括号里面是切入点是哪个 public void before(){ System.out.println("开启事务"); } @AfterReturning("pointcut()") public void after(){ System.out.println("提交事务"); } }
这样表达式可以不用写那么多遍了.直接这样调入切入点就可以了