码迷,mamicode.com
首页 > 编程语言 > 详细

Spring之AOP实现面向切面编程

时间:2017-05-25 10:12:09      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:alt   依赖包   安装   文件   img   显示   spec   src   ram   

近期在学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>


//程序依赖包和结果

技术分享





Spring之AOP实现面向切面编程

标签:alt   依赖包   安装   文件   img   显示   spec   src   ram   

原文地址:http://www.cnblogs.com/zsychanpin/p/6901869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!