Spring AOP使用步骤

在Spring中使用AOP编程步骤:


以下使用的Spring为2.5.6版本


1、在Spring配置文件(applicationContext.xml)中配置Spring对AspectJ的支持;以下两种方式任意一种即可

     <!-- <aop:aspectj-autoproxy/> -->
    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>


2、引入Jar文件(在Spring的根目录下的lib/aspectj下)

     aspectjrt.jar  和  aspectjweaver.jar


3、定义连接点(若不使用接口编程,即SimplePersonManager不实现任何接口,此时要实现AOP代理,需要引入CGLIB 包cglib-nodep-2.1_3.jar,但是一旦实现了接口Spring就会使用JDK的动态代理实现)

 

public interface PersonManager {

	public void addPerson(Person person);
}

 

public class SimplePersonManager implements PersonManager{

	public void addPerson(Person person) {
		Person.persons.add(person);
                System.out.println("添加了一个用户");
	}
}
 

 

4、定义一个切面类,该切面类中定义了一个切入点,连接点为SimplePersonManager类中的addPerson方法

 

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class SimpleAspect {

	@Before ("execution (* rote.spring.aop.service.impl.SimplePersonManager.addPerson(..))")
	public void addPersonAop(){
		System.out.println("-------------------addPerson-----------------------");
	};
	
}

 

5、在Spring配置文件中声明切面类

    <!-- 切面声明 -->
    <bean id="simpleAspectj" class="rote.spring.aop.aspectj.SimpleAspect">
    </bean>


6、在Spring配置文件中配置连接点类

     <bean id="personManager" class="rote.spring.aop.service.impl.SimplePersonManager">
    </bean>


7、启动测试

 

ApplicationContext context = new ClassPathXmlApplicationContext("rote/spring/aop/applicationContext-aop.xml");
		
PersonManager personManager = (PersonManager)context.getBean("personManager");
		
personManager.addPerson(new Person());

 上述代码运行后,将输出如下结果,在调用addPerson方法之前执行了addPersonAop方法:

-------------------addPerson-----------------------
添加了一个用户

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值