开启注解
<!-- 1配置目标对象 -->
<bean name="userService" class="com.itheima.service.UserServiceImpl"></bean>
<!-- 2配置通知 -->
<bean name="myAdvice" class="com.itheima.annotationaop.Myadvice"></bean>
<!-- 3开启使用注解完成织入 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
在通知类注解
//这个注解表示一个通知类
@Aspect
public class Myadvice {
@Pointcut("execution(* com.itheima.service.*ServiceImpl.*(..))")
public void pc(){};
//指定该方法是前置通知,并指定切入点
public void before(){
System.out.println("这是前置通知");
}
@AfterReturning("Myadvice.pc()")
public void afterReturning(){
System.out.println("后置通知,异常不调用");
}
@Around("Myadvice.pc()")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("这是环绕通知之前的部分");
Object proceed = pjp.proceed();
System.out.println("这是环绕通知之后的部分");
return proceed;
}
@AfterThrowing("Myadvice.pc()")
public void afterException(){
System.out.println("出现异常了");
}
@After("Myadvice.pc()")
public void after(){
System.out.println("后置通知,异常也调用");
}
}
编写测试类
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.itheima.domain.User;
import com.itheima.service.UserService;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:com/itheima/annotationaop/applicationContext.xml")
public class TestDemo {
//将名为user的对象注入u中
@Resource(name="userService")
private UserService us;
@Test
public void fun(){
us.save();
}
输出结果