Spring之AOP实现面向切面编程

最近在学Java的动态代理和Spring面向切面编程,越来越觉得Spring设计的真的是太完美了。于是,想一个最简单的例子来跑一下,但问题多多,显示缺少,Aspectj里面的对应的类,导入Aspectj.jar呗,但是装Aspectj.jar跟一般的导入.jar不一样,还需要安装并修改Path变量,添加安装目录下的bin目录到PATH中,并将安装目录下lib目录里的.jar文件导入MyEclipse;然后,又出现了NoSuchMethodError: net.sf.cglib.proxy.Enhancer.setInterceptDuringConstruction(Z)V错误,于是又找cglib.jar包,导入.jar包,依然是同样的错误,搜了搜,原来是应该导入cglib-nodep-2.1_3.jar而不是cglib2.jar,导入完成,问题解决,bravo!

//AOPTest.java

package com.spring.aop;

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

public class AOPTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx=new ClassPathXmlApplicationContext("aop.xml");
		Consume consume=(Consume)ctx.getBean("consume");
		consume.consumeService();
	}

}

//Consume.java

package com.spring.aop;

public class Consume {
	public void consumeService()
	{
		System.out.println("The food is delicious!");
	}
}	


//Service.java

package com.spring.aop;

public class Service {
	public void beforConsume()
	{
		System.out.println("Before consume!");
	}
	public void afterConsume()
	{
		System.out.println("After consume!");
	}
}

//配置文件

<?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-3.0.xsd">
	<bean name="service" class="com.spring.aop.Service"/>
	<bean name="consume" class="com.spring.aop.Consume"/>
	<aop:config>
		<aop:aspect ref="service">
			<aop:pointcut id="consumeService" expression="execution(* *.consumeService(..))" />
			<aop:before pointcut-ref="consumeService" method="beforConsume"/>
			<aop:after pointcut-ref="consumeService" method="afterConsume"/>
		</aop:aspect>
	</aop:config>
</beans>


//程序依赖包和结果






你可能感兴趣的:(AOP,aspectj,cglib)