这里模拟一个用户添加和删除前后需要做权限检查和日志记录的工作:
UserService----抽象对象
UserServiceImpl----被代理对象
UserServiceImplProxy----代理对象
public interface UserService {
//添加方法
void add();
//删除方法
void del();
}
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("用户被添加...");
}
public void del() {
System.out.println("用户被删除...");
}
}
public class UserServiceImplProxy implements UserService{
public UserServiceImpl u = new UserServiceImpl();
public void add() {
check();
u.add();
log();
}
public void del() {
check();
u.del();
log();
}
//用户添加或者删除前需要检查是否有权限操作
public void check(){
System.out.println("权限检查通过...");
}
//用户删除后需要记录日志
public void log(){
System.out.println("日志记录成功...");
}
}
applicationContext.xml
<!--创建UserServiceImplProxy代理对象-->
<bean id="proxy" class="com.msb.proxy.UserServiceImplProxy"/>
测试类
public class ProxyTest {
ApplicationContext app;
@Before
public void init(){
//加载配置文件
app = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test1() {
UserService user = (UserService)app.getBean("proxy");
user.add();
user.del();
}
}
运行结果