一.第一步
1.导入jar包
2.编写目标方法
@Service
public class StudentService {
public boolean save(String name) {
System.out.println("StudentService...save");
return true;
}
}
3.配置文件
<?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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
default-autowire="byName">
<!-- 扫描注解的基包 -->
<context:component-scan base-package="cn.wang"/>
<!-- 开启AspectJ自动代理 -->
<aop:aspectj-autoproxy/>
</beans>
4.使用注解配置增强处理
@Component
@Aspect
public class StudentAdvice {
@Before(value="execution(* cn.wang.service..*(..))")
public void before(JoinPoint joinPoint) {
System.out.println("这是前置增强方法");
}
@AfterReturning(value="execution(* cn.wang.service..*(..))")
//如果目标方法有返回值,后置增强不管配部配returning 都会执行
// 环绕增强必须接受返回值
//如果目标方法没有返回值,后置增强配置了returning 则 后置增强不会执行
public void after(JoinPoint joinPoint) {
System.out.println("这是后置增强方法");
}
@After(value="execution(* cn.wang.service..*(..))")
public void finalAfter() {
System.out.println("这是最终增强方法");
}
@AfterThrowing(value="execution(* cn.wang.service..*(..))",throwing="e")
public void throwAdvice(JoinPoint joinPoint,Exception e) {
System.out.println("这是异常增强方法");
}
@Around(value="execution(* cn.wang.service..*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("这是环绕增强方法");
Object proceed = joinPoint.proceed();
System.out.println("hou");
return proceed;
}
}
5.测试
public class TestStudent {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
StudentService bean = (StudentService) context.getBean("studentService");
bean.save("张三");
}
}