您的位置:首页 > 编程语言 > ASP

SSM框架项目搭建系列(七)—Spring AOP之基于注解的声明式AspectJ

2016-11-03 19:18 861 查看
工程结构



其中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();
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: