AOP的MethodBeforeAdvice

使用Spring自动生成代理类,spring利用的是动态代理机制

接口

Java代码

publicinterfaceUserDao{

voidaddUser();

voiddeleteUser();

}

两个实现:

Java代码

publicclassUserDaoMySqlImplimplementsUserDao{

@Override

publicvoidaddUser(){

System.out.println("UserDaoMySqlImpl.addUser()");

}

@Override

publicvoiddeleteUser(){

System.out.println("UserDaoMySqlImpl.deleteUser()");

}

}

publicclassUserDaoOracleImplimplementsUserDao{

@Override

publicvoidaddUser(){

System.out.println("UserDaoOracleImpl.addUser()");

}

@Override

publicvoiddeleteUser(){

System.out.println("UserDaoOracleImpl.deleteUser()");

}

}

Device

importjava.lang.reflect.Method;

importorg.springframework.aop.MethodBeforeAdvice;

publicclassUserDaoBeforeAdviceimplementsMethodBeforeAdvice{

@Override

publicvoidbefore(Methodarg0,Object[]arg1,Objectarg2)

throwsThrowable{

System.out.println("UserDaoBeforeAdvice.before()");

}

}

spring的配置文件

Xml代码

<!--配置实现类的bean,可以把所有的实现类都写上-->

<beanid="userdao"class="com.dowebber.spring.aop.UserDaoMySqlImpl"></bean>

<!--配置Advice的bean-->

<beanid="beforeadvice"class="com.dowebber.spring.aop.UserDaoBeforeAdvice"></bean>

<!--配置spring自动生成代理对象所需要的一些参数-->

<beanid="userdaoproxy"class="org.springframework.aop.framework.ProxyFactoryBean">

<propertyname="proxyInterfaces"value="com.dowebber.spring.aop.UserDao"/>

<propertyname="target">

<refbean="userdao"/>

</property>

<propertyname="interceptorNames">

<list>

<value>beforeadvice</value>

</list>

</property>

</bean>

测试类:

Java代码

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

publicclassTestUserDaoBeforeDevice{

publicstaticvoidmain(String[]args){

ApplicationContextcontext=newClassPathXmlApplicationContext("com/dowebber/spring/aop/spring.xml");

UserDaodao=(UserDao)context.getBean("userdaoproxy");

dao.addUser();

}

}

相关推荐