动态代理

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

public class CustomBeanPostProcessor implements BeanPostProcessor{
    //了解生存周期
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)  {
        Object change = Enhancer.create(bean.getClass(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("hello ");
                Object invoke = method.invoke(bean,objects);
                System.out.println(" world");
                return invoke;
            }
        });

        return change;
    }
}
    
    
    
 @Test
    public void mytest2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        Cat cat1 = applicationContext.getBean(Cat.class);
        cat1.say();
        Dog dog = applicationContext.getBean(Dog.class);
        dog.say();
    }

 

你可能感兴趣的:(JAVA)