Spring的切面編程例子

1.在Spring入門實例的基礎上添加一個攔截器(Spring的AOP也需要實現特定的接口。Spring把這些實現了特定AOP接口的類稱爲攔截器):

package com.spring.impl;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.springframework.aop.MethodBeforeAdvice;

public class MethodBeforeAdviceImpl implements MethodBeforeAdvice
{
	@Override
	public void before(Method method, Object[] args, Object obj)
			throws Throwable {
		System.out.println("運行前檢查......");
		System.out.println("method:"+method.getName());
		System.out.println("Args:"+Arrays.asList(args));
		System.out.println("Objects:"+obj);
		
	}
}


 

2.修改配置文件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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!-- 配置攔截器對象 -->
	<bean id="methodBeforeAdviceImpl" class="com.spring.impl.MethodBeforeAdviceImpl"></bean>
	<bean id="theAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
	    <property name="advice">
	        <ref local="methodBeforeAdviceImpl"/>
	    </property>
	    <property name="mappedName" value="*"></property><!-- 攔截所有的方法 -->
	</bean>
	<bean id="daoImpl" class="com.spring.impl.DaoImpl"></bean>
	<bean id="serviceImpl" class="com.spring.service.ServiceImpl">
	    <property name="idao" ref="daoImpl"></property>
	</bean>
	<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
	    <property name="interceptorNames" value="theAdvisor"></property>
	    <property name="target">
	        <ref local="serviceImpl"/>
	    </property>
	</bean>
</beans>


 

3.測試類中將獲取的bean改爲代理類的id:

package com.spring.junit;

import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.spring.inter.IService;

public class test1 
{
	@Test
	public void test()
	{
		XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("applicationContext.xml"));
		
		IService hello =(IService) factory.getBean("proxy");
		hello.service("HelloBean");
		factory.destroySingletons();
	}
}


運行結果爲:

log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
運行前檢查......
method:service
Args:[HelloBean]
Objects:com.spring.service.ServiceImpl@1968e23
早上好,HelloBean

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章