题目-使用spring为项目里的所有类的所有方法增加

本文介绍如何使用Spring的BeanPostProcessor接口,结合ProxyUtil,实现在Animal接口的Cat、Dog、Tiger类实例调用call方法前后的日志记录,包括'hello'和'world'。适合理解动态代理在Spring中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写几个不同的bean (实现同一个接口),每个bean里有这些接口的不同实现方法。
通过spring 使得调用任何一个实现方法之前和之后都增加一些log。(通过PostBeanProcessor实现)

举例:比如有几个类Cat、Dog、Tiger,这几个类中分别有miao、wang、wuuu这几个方法,那么从容器中取出组件,调用这几个方法的时候(注意不是容器初始化时),miao、wang、wuuu这几个方法执行之前都会输出hello,执行之后都会输出world。

提示:生命周期 动态代理 是调用方法的时候,而不是容器初始化的时候

在这里插入图片描述
实现代码:
在这里插入图片描述
Animal

public interface Animal {
    void call();
}

Cat

@Repository
public class Cat implements Animal{

    public void call() {
        System.out.println("miao");
    }
}

Dog

@Repository
public class Dog implements Animal {
    public void call() {
        System.out.println("wang");
    }
}

Tiger

@Repository
public class Tiger implements Animal {
    public void call() {
        System.out.println("wuuu");
    }
}

LifeCycleBean

@Component
public class LifeCycleBean implements BeanPostProcessor {
    public LifeCycleBean(){
        super();
    }

    public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
        bean=ProxyUtil.getServiceProxy(bean.getClass());
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException{
        return bean;
    }
}

ProxyUtil

public class ProxyUtil {
    public static <T> T getServiceProxy(final Class<T> tClass){
        T proxy=(T) Enhancer.create(tClass, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                T t=tClass.newInstance();
                System.out.println("hello");

                Object invoke=method.invoke(t,objects);
                System.out.println("world");
                System.out.println("---------------");
                return invoke;
            }
        });
        return proxy;
    }

}

application
在这里插入图片描述
AnimalTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class AnimalTest {



    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    LifeCycleBean lifeCycleBean;

    @Autowired
    Cat cat;
    @Autowired
    Dog dog;
    @Autowired
    Tiger tiger;

    @Test
    public void  testAnimal(){

        cat.call();
        dog.call();
        tiger.call();
    }
}

结果;
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值