<?xml version="1.0" encoding="GBK"?>
使用Spring自动生成代理类,spring利用的是动态代理机制
接口
Java代码
public interface UserDao {
void addUser();
void deleteUser();
}
public interface UserDao {
void addUser();
void deleteUser();
}
两个实现:
Java代码
public class UserDaoMySqlImpl implements UserDao {
@Override
public void addUser() {
System.out.println("UserDaoMySqlImpl.addUser()");
}
@Override
public void deleteUser() {
System.out.println("UserDaoMySqlImpl.deleteUser()");
}
}
public class UserDaoOracleImpl implements UserDao {
@Override
public void addUser() {
System.out.println("UserDaoOracleImpl.addUser()");
}
@Override
public void deleteUser() {
System.out.println("UserDaoOracleImpl.deleteUser()");
}
}
Device
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class UserDaoBeforeAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("UserDaoBeforeAdvice.afterReturning()");
}
}
public class UserDaoMySqlImpl implements UserDao {
@Override
public void addUser() {
System.out.println("UserDaoMySqlImpl.addUser()");
}
@Override
public void deleteUser() {
System.out.println("UserDaoMySqlImpl.deleteUser()");
}
}
public class UserDaoOracleImpl implements UserDao {
@Override
public void addUser() {
System.out.println("UserDaoOracleImpl.addUser()");
}
@Override
public void deleteUser() {
System.out.println("UserDaoOracleImpl.deleteUser()");
}
}
Device
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class UserDaoBeforeAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
System.out.println("UserDaoBeforeAdvice.afterReturning()");
}
}
配置文件
Xml代码
<!-- 配置实现类的bean,可以把所有的实现类都写上 -->
<bean id="userdao" value="com.dowebber.spring.aop_after.UserDao"/>
<property name="target">
<ref bean="userdao"/>
</property>
<property name="interceptorNames">
<list>
<value>beforeadvice</value>
</list>
</property>
</bean>
<!-- 配置实现类的bean,可以把所有的实现类都写上 -->
<bean id="userdao" value="com.dowebber.spring.aop_after.UserDao"/>
<property name="target">
<ref bean="userdao"/>
</property>
<property name="interceptorNames">
<list>
<value>beforeadvice</value>
</list>
</property>
</bean>
测试类
Java代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestUserDaoAfterDevice {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/dowebber/spring/aop_after/spring.xml");
UserDao dao = (UserDao)context.getBean("userdaoproxy");
dao.addUser();
}
}