================接口類TimeBookInterface ==============
package com.gc.action.springaop;
/**
* 接口類
* @author yltd
*
*/
public interface TimeBookInterface {
public void doSameing(String name);
}
==============接口實(shí)現(xiàn)類TimeBookImpl ======================
package com.gc.action.springaop;
/**
* 接口實(shí)現(xiàn)類
* @author yltd
*
*/
public class TimeBookImpl implements TimeBookInterface {
@Override
public void doSameing(String name) {
System.out.println(name);
}
}
===============日志輸出類LogAround ==================
package com.gc.action.springaop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* AOP實(shí)現(xiàn)輸出日志
* @author yltd
*
*/
public class LogAround implements MethodInterceptor {
Logger logger =Logger.getLogger(this.getClass().getName());
@Override
public Object invoke(MethodInvocation arg) throws Throwable {
logger.log(Level.INFO, "開始。。。");
Object obj = arg.proceed();
logger.log(Level.INFO, "結(jié)束。。。");
return obj;
}
}
=============XML配置文件config.xml==================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 負(fù)責(zé)國(guó)際化支持 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 國(guó)際化支持的定義在文件名為messages的文件中 -->
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="log" class="com.gc.action.springaop.LogAround"></bean>
<bean id="timeBook" class="com.gc.action.springaop.TimeBookImpl"></bean>
<bean id="logProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.gc.action.springaop.TimeBookInterface</value>
</property>
<property name="target">
<ref bean="timeBook"/>
</property>
<!-- 指定要代理的類 -->
<property name="interceptorNames">
<list>
<value>log</value>
</list>
</property>
</bean>
</beans>
====================測(cè)試類TestMain ================
package com.gc.action.springaop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* 測(cè)試類
* @author yltd
*
*/
public class TestMain {
public static void main(String[] args) {
ApplicationContext ac =new FileSystemXmlApplicationContext("classpath:/SpringConfig.xml");
TimeBookInterface tbi=(TimeBookInterface) ac.getBean("logProxy");
tbi.doSameing("張藝馨");
}
}
====================結(jié)果======================
- Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@4e515669: startup date [Fri Oct 19 16:13:27 CST 2018]; root of context hierarchy
- Loading XML bean definitions from class path resource [SpringConfig.xml]
- 開始。。。
張藝馨
- 結(jié)束。。。