spring入门实例-aop
?
spring入门实例-aop?
使用interceptor模式实现advice
实例:
配置databaseaop.xml
?
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><description>database aop</description><bean id="logInterceptor" /></property><property name="interceptorNames"><list><value>logInterceptor</value><value>OracleInterceptor</value></list></property></bean></beans>
?
?
interactor的监控接口:
?
public interface IHello{public String hello(String name);public void morning(String name);}
?
?接口的实现类:
?
public class DataBaseSpeaker implements IHello{@Overridepublic String hello(String name){System.out.println("mysql,"+name);return name;}@Overridepublic void morning(String name){System.out.println("oracle,"+name);}public static void main(String[] args){ApplicationContext context = new ClassPathXmlApplicationContext("com/myspring/aop/databaseaop.xml");IHello helloProxy = (IHello) context.getBean("dbproxy");helloProxy.hello("227");helloProxy.morning("momor");}}
?
?
两个interceptor
?
public class LogInterceptor implements MethodInterceptor{private Logger logger = Logger.getLogger(this.getClass().getName());@Overridepublic Object invoke(MethodInvocation methodInvocation) throws Throwable{logger.log(Level.INFO, "method stats...");System.out.println("ffffffffffffffffff");try{Object result = methodInvocation.proceed();System.out.println(result);return result;}finally{logger.log(Level.INFO, "method ends.."+methodInvocation.getMethod());System.out.println("eeeeeeeeeeeeeeeeeee");}}}
?public class OracleInterceptor implements MethodInterceptor
{@Overridepublic Object invoke(MethodInvocation methodInvocation) throws Throwable{// TODO Auto-generated method stubSystem.out.println("qqqqqqqqqqqqMethodInvocation");Object obj = methodInvocation.proceed();System.out.println("qqqqqqqqqqqqMethodInvocation");return obj;}}?
public class OracleInterceptor implements MethodInterceptor{@Overridepublic Object invoke(MethodInvocation methodInvocation) throws Throwable{// TODO Auto-generated method stubSystem.out.println("qqqqqqqqqqqqMethodInvocation");Object obj = methodInvocation.proceed();System.out.println("qqqqqqqqqqqqMethodInvocation");return obj;}}?
测试main:
public static void main(String[] args){ApplicationContext context = new ClassPathXmlApplicationContext("com/myspring/aop/databaseaop.xml");IHello helloProxy = (IHello) context.getBean("dbproxy");helloProxy.hello("227");helloProxy.morning("momor");}?
?
?
?
?