spring aop 初探

阿超 发表于 2010-03-20 10:44 | 来源: | 阅读 115 次

spring aop 初探了解 通知,切点,目标对象,代理对象

1.建一个application工程aopTest

2.导入相应的包(这里用的spring2.5.X)

3.创建目标类LogTarget

public class LogTarget {
	public void login(){
		System.out.println("login is run");
	}
}

4.创建通知类LogAdvice

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class LogAdvice implements MethodBeforeAdvice{

	@Override
	public void before(Method arg0, Object[] arg1, Object arg2)
			throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("befor is run");
	}

}

5.配置applicationContext.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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 目标对象 -->
	<bean id="logTarget" class="LogTarget"/>
	<!-- 通知 -->
	<bean id="logAdvice" class="LogAdvice"/>
	<!-- 切入点 -->
	<bean id="logPointCutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="advice">
			<ref bean="logAdvice"/>
		</property>
		<property name="pattern">
			<value>.*login.*</value>
		</property>
	</bean>
	<!-- 代理对象 -->
	<bean id="logProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="target">
			<ref bean="logTarget"/>
		</property>
		<property name="interceptorNames">
			<list>
				<value>logPointCutAdvisor</value>
			</list>
		</property>
	</bean>
</beans>

6.编写测试类TestMain

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

public class TestMain {
	public static void main(String[] args) {
		ApplicationContext ctx = new FileSystemXmlApplicationContext(
				"src/applicationContext.xml");
		LogTarget logtarget=(LogTarget)ctx.getBean("logProxy");
		logtarget.login();
	}
关键字: ,
喜欢Java豆技术站点的文章,那就通过 RSS Feed 功能订阅阅读吧!

才1个评论

  1. Firm 说:

    叫深入研究了,针对我而言

我要评论

*

* 绝不会泄露



返回首页 | 关于我们 | 联系我们 | 广告合作 | 网站地图 | 友情链接 | 版权声明 | 模板设计