spring代理对象怎么创建
在Spring中,可以使用两种方式来创建代理对象:
- 使用JDK动态代理:JDK动态代理是通过接口来实现的代理方式。首先,需要定义一个接口,然后创建一个实现该接口的实现类,并且实现具体的业务逻辑。接下来,创建一个InvocationHandler接口的实现类,该类中实现了invoke方法,用于在代理对象的方法被调用时进行处理。最后,使用Proxy类的静态方法newProxyInstance来创建代理对象。
public interface UserService {
void addUser(String name);
}
public class UserServiceImpl implements UserService {
@Override
public void addUser(String name) {
System.out.println("Add user: " + name);
}
}
public class UserServiceInvocationHandler implements InvocationHandler {
private Object target;
public UserServiceInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method: " + method.getName());
return result;
}
}
public class Main {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
UserServiceInvocationHandler handler = new UserServiceInvocationHandler(userService);
UserService proxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(), handler);
proxy.addUser("John");
}
}
- 使用CGLIB动态代理:CGLIB动态代理是通过继承来实现的代理方式。首先,需要定义一个类,然后创建一个继承该类的子类,并且重写父类的方法,实现具体的业务逻辑。接下来,创建一个MethodInterceptor接口的实现类,该类中实现了intercept方法,用于在代理对象的方法被调用时进行处理。最后,使用Enhancer类的create方法来创建代理对象。
public class UserService {
public void addUser(String name) {
System.out.println("Add user: " + name);
}
}
public class UserServiceInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = proxy.invokeSuper(obj, args);
System.out.println("After method: " + method.getName());
return result;
}
}
public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
enhancer.setCallback(new UserServiceInterceptor());
UserService proxy = (UserService) enhancer.create();
proxy.addUser("John");
}
}
无论使用JDK动态代理还是CGLIB动态代理,都需要创建一个InvocationHandler或MethodInterceptor的实现类,并在其中实现具体的代理逻辑。然后,通过相应的方式创建代理对象,并将代理对象用于执行相应的方法。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:买空间搭建网站需要哪些配置 下一篇:Java怎么生成树形结构数据
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。