工程结构
其中AOP和com.ssm包下面的文件不用管;dispatcher-servlet.xml和web.xml和之前项目中的内容一样。
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: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.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:component-scan base-package="AOP2"/>
<!--启动@AspectJ支持 默认是false-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
Person.java
package AOP2;
import org.springframework.stereotype.Component;
/**
* DateTime: 2016/11/2 21:35
* 功能:
* 思路:
*/
@Component
public class Person {
public void eatBreakfast(){
System.out.println("......eatBreakfast()早餐......");
}
public void eatLunch(){
System.out.println("......eatLunch()午餐......");
}
public void eatSupper(){
System.out.println("......eatSupper()晚餐......");
}
}
AdivceMethod.java
package AOP2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* DateTime: 2016/11/2 21:40
* 功能:
* 思路:
*/
@Component
@Aspect
public class AdivceMethod {
@Before("execution(* AOP2.Person.*(..))") //匹配Person中的所有方法
public void beforeEat(){
System.out.println("...吃饭之前洗手...");
}
@After("execution(* AOP2.Person.eatLunch())") //匹配eatLunch方法
public void afterEat(){
System.out.println("...吃饭之后洗碗...");
}
@Around("execution(* AOP2.Person.eatSupper())") //匹配eatSupper方法
public Object aroundEat(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("........吃饭前先逛一逛........");
Object value = proceedingJoinPoint.proceed();
System.out.println("........吃完后要睡觉了........");
return value;
}
}
AopTest.java
package AOP2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* DateTime: 2016/11/2 22:10
* 功能:
* 思路:
*/
public class AopTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
AOP2.Person person= (AOP2.Person) context.getBean("person");
System.out.println();
person.eatBreakfast();
System.out.println();
person.eatLunch();
System.out.println();
person.eatSupper();
System.out.println();
}
}