AOP的MethodAfterAdvice
使用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.AfterReturningAdvice;
publicclassUserDaoBeforeAdviceimplementsAfterReturningAdvice{
@Override
publicvoidafterReturning(Objectarg0,Methodarg1,Object[]arg2,
Objectarg3)throwsThrowable{
System.out.println("UserDaoBeforeAdvice.afterReturning()");
}
}
配置文件
Xml代码
<!--配置实现类的bean,可以把所有的实现类都写上-->
<beanid="userdao"class="com.dowebber.spring.aop_after.UserDaoMySqlImpl"></bean>
<!--配置Advice的bean-->
<beanid="beforeadvice"class="com.dowebber.spring.aop_after.UserDaoBeforeAdvice"></bean>
<!--配置spring自动生成代理对象所需要的一些参数-->
<beanid="userdaoproxy"class="org.springframework.aop.framework.ProxyFactoryBean">
<propertyname="proxyInterfaces"value="com.dowebber.spring.aop_after.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;
publicclassTestUserDaoAfterDevice{
publicstaticvoidmain(String[]args){
ApplicationContextcontext=newClassPathXmlApplicationContext("com/dowebber/spring/aop_after/spring.xml");
UserDaodao=(UserDao)context.getBean("userdaoproxy");
dao.addUser();
}
}