大家好,又见面了,我是你们的朋友全栈君。
接口的动态代理
- 事务
两种结果:提交 回滚
提交:发生在return
回滚:全回滚 / 回滚到定义的保存点
接口:
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("addUser");
}
}
测试类:
@Test
public void t3(){
final UserServiceImpl userService=new UserServiceImpl();
/* * ClassLoader loader, 一般调用当前类的类加载器 * Class<?>[] interfaces, * InvocationHandler h * */
InvocationHandler handler= new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开启事务");
Object object= method.invoke(userService,args);
System.out.println("关闭事务");
return object;
}
};
UserService userServiceProxy= (UserService) Proxy.newProxyInstance(Test01.class.getClassLoader(),
UserServiceImpl.class.getInterfaces(),handler );
userServiceProxy.addUser();
}
统一事务处理
统一事务处理类:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/* * 重写了 BeanPostProcessor * 配置的方法非常简单,只要配置给容器就可以了 * */
public class MyBeanPostProcess implements BeanPostProcessor{
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Before-Initialization");
System.out.println(bean);
System.out.println(beanName);
return bean;
}
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
System.out.println("After-Initialization");
if(beanName.equals("userService" )){
InvocationHandler handler= new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开启事务");
Object object= method.invoke(bean,args);
System.out.println("关闭事务");
return object;
}
};
// BeanPostProcessor全局生效 需要使用名称进行过滤
return Proxy.newProxyInstance(MyBeanPostProcess.class.getClassLoader(),
bean.getClass().getInterfaces(),handler);
}else {
return bean;
}
}
}
applicationContext.xml配置;
<bean class="com.xbj.dao.impl.UserServiceImpl" id="userService" />
<bean class="com.xbj.dao.MyBeanPostProcess" />
<!--配置BeanPostProcess 全局生效-->
userService:
public interface UserService {
void addUser();
}
UserServiceImpl:
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("addUser");
}
}
测试类:
private ClassPathXmlApplicationContext context;
@Before
public void t1(){
context= new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void t2(){
UserService userService=context.getBean("userService",UserService.class);
userService.addUser();
context.close();
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/106641.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...