spring aop 完整实例

Employe.java
package com.aop;

public interface Employee {
public void signIn();

}


CommonEmployee.java
package com.aop;

public class CommonEmployee implements Employee{

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void signIn() {
System.out.println(name+" is very beautiful");
}
}


AspectJLogger.java
package com.aop;
import java.util.Date;
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;


@Aspect
public class AspectJLogger {

public static final String EDP = "execution(* com.aop.CommonEmployee.sign*(..))";

@Before(EDP) //spring中Before通知
public void logBefore() {
System.out.println("logBefore:现在时间是:"+new Date());
}

@After(EDP) //spring中After通知
public void logAfter() {
System.out.println("logAfter:现在时间是:"+new Date());
}

@Around(EDP) //spring中Around通知
public Object logAround(ProceedingJoinPoint joinPoint) {
System.out.println("logAround开始:现在时间是:"+new Date()); //方法执行前的代理处理
Object[] args = joinPoint.getArgs();
Object obj = null;
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("logAround结束:现在时间是:"+new Date()); //方法执行后的代理处理
return obj;
}
}



aa.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" >


<aop:aspectj-autoproxy/>
<bean id="aspect" class="com.aop.AspectJLogger" />
<bean id="employee" class="com.aop.CommonEmployee">
<property name="name" value="zouhuiying"></property>
</bean>

</beans>



Test.java
package com.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.aop.Employee;

public class Test {
public static void main(String[] args) throws Exception{
ApplicationContext act = new ClassPathXmlApplicationContext("aa.xml");
Employee e = (Employee)act.getBean("employee");
e.signIn();

}
}



执行结果
logAround开始:现在时间是:Mon Feb 29 16:13:01 CST 2016
logBefore:现在时间是:Mon Feb 29 16:13:01 CST 2016
zouhuiying is very beautiful
logAround结束:现在时间是:Mon Feb 29 16:13:01 CST 2016
logAfter:现在时间是:Mon Feb 29 16:13:01 CST 2016
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值