`

jdk6.0从入门到精通-----chapter16反射机制-spring AOP

阅读更多
spring aop的简单示例
新建java项目,添加spring的core和aop库

简单的业务接口
package net.soho.test.spring.aop;

public interface IHello {

	public String getContent(String h);
}


简单的业务类
package net.soho.test.spring.aop;

public class Hello implements IHello {

	public String getContent(String h) {
		return h;
	}

}


实现MethodBeforeAdvice 接口的
package net.soho.test.spring.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class LoggingBeforeAdvice implements MethodBeforeAdvice {

	public void before(Method arg0, Object[] arg1, Object arg2)
			throws Throwable {
		// TODO Auto-generated method stub
		
		System.out.println("业务方法开始执行.....");

	}

}


主调程序HelloClient.java
package net.soho.test.spring.aop;

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

public class HelloClient {
	public static void main(String[] args) {

		[color=red]Resource resource = new ClassPathResource("applicationContext.xml");
		org.springframework.beans.factory.BeanFactory factory= new XmlBeanFactory(resource);[/color]		IHello h=  (IHello) factory.getBean("hellobean");
		System.out.println(h.getContent("多啦A梦"));
	}

}

红色部分为读取spring配置文件的一般写法

spring配置文件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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	<bean id="hellobean"
		class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyInterfaces">
			<value>net.soho.test.spring.aop.IHello</value>
		</property>
		<property name="target">
			<ref local="hellobeanTarget" />
		</property>
		<property name="interceptorNames">
			<list>
				<value>loggingBeforeAdvisor</value>
			</list>
		</property>
	</bean>
	<bean id="hellobeanTarget" class="net.soho.test.spring.aop.Hello"></bean>
	<bean id="loggingBeforeAdvisor"
		class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="advice">
			<ref local="loggingBeforeAdvice"></ref>
		</property>
		<property name="pattern">
			<value>.*</value>
		</property>
	</bean>
	<bean id="loggingBeforeAdvice"
		class="net.soho.test.spring.aop.LoggingBeforeAdvice">
	</bean>
</beans>



执行结果:

log4j:WARN No appenders could be found for logger (org.springframework.util.ClassUtils).
log4j:WARN Please initialize the log4j system properly.
业务方法开始执行.....
多啦A梦


前两行是因为没有设置日志出现的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics