Spring 对某个对象进行代理(aop的功能,可以对某个功能进行开关)

在这里插入图片描述

  • EnableLuban
@Retention(RetentionPolicy.RUNTIME)
@Import(MyImportSelector.class)
public @interface EnableLuban {
}
  • Appconfig
@ComponentScan("com.luban")
@EnableLuban  //开启代理功能,去掉就不会对IndexDao进行代理
public class Appconfig {
    @Bean
    public IndexDao indexDao(){
        return  new IndexDao();
    }
}
  • Dao
public interface Dao {
    public void query();
}
  • IndexDao
public class IndexDao implements Dao{
    @Override
    public void query() {
        System.out.println("indexDao");
    }
}
  • IndexDao3
//对IndexDao进行代理
public class IndexDao3 implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("indexDao")){
            bean = Proxy.newProxyInstance(bean.getClass().getClassLoader(), new Class[]{Dao.class}, new MyInvocationHandler(bean));
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

}
  • MyImportSelector
public class MyImportSelector implements ImportSelector {
	//作用就是代替@Component
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{IndexDao3.class.getName()};
    }
}
  • MyInvocationHandler
public class MyInvocationHandler implements InvocationHandler {
    Object target;
    public MyInvocationHandler(Object target){
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("我是代理方法");
        return method.invoke(target, args);
    }
}
  • test
public class test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext(Appconfig.class);
        Dao dao = (Dao) annotationConfigApplicationContext.getBean("indexDao"); 
        //这里返回的是一个代理对象,不能用IndexDao接收
        dao.query();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值