我爱熊猫

导航

<2025年4月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

留言簿(1)

文章分类

文章档案

最新评论

spring aop 之一注释方式

前篇采用传统方式的aop配置稍显麻烦,这篇带来的是spring2.5支持的采用annotation方式的aop实现.

先看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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="helloService" class="cn.com.ultrapower.service.HelloServiceImpl">
</bean>
<bean id="helloAction" class="cn.com.ultrapower.action.HelloActionImpl">
<!-- setter injection using the nested <ref/> element -->
<property name="helloService"><ref bean="helloService"/></property>
<!--property可以不设置类型 -->
<property name="name" value="yoo"></property>
</bean>
<bean id="logAdvisor" class="cn.com.ultrapower.advice.annotation.LogAdvisor">
</bean>
</beans>

与前篇的不一样的地方是增加了<aop:aspectj-autoproxy/>,这样就可以让spring支持自动配置.另外helloAction变的简单了,只需要应用helloService就可以了.HelloActionImpl中也不需要特殊设置.关键的地方在LogAdvisor,看下面代码:

@Aspect
public class LogAdvisor {

/**
* 定义一个切点
*/
@Pointcut("execution(* cn.com.ultrapower.action.IHelloAction.*(..))")
public void someMethod() {
/*
* 下面语句不会显示
*/
System.out.println("Log:on method!");
}

@AfterReturning("someMethod()")
public void before() {
System.out.println("Log:before method!");
}

@Before("someMethod()")
public void after() {
System.out.println("Log:after method!");
}
}

注意下面点:

1 类名前加上@Aspect表示这是一个切面。

2 使用@Pointcut("execution(* cn.com.ultrapower.action.IHelloAction.*(..))")
定义一个切点,在IHelloAction的任何方法中切入。具体用法参看spring文档。

3 @AfterReturning("someMethod()") 创建一个前置监听器。

4 @Before("someMethod()")创建一个后置监听器。


posted on 2008-06-07 20:33 flyoo 阅读(345) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: