天天看點

題目-使用spring為項目裡的所有類的所有方法增加

寫幾個不同的bean (實作同一個接口),每個bean裡有這些接口的不同實作方法。

通過spring 使得調用任何一個實作方法之前和之後都增加一些log。(通過PostBeanProcessor實作)

舉例:比如有幾個類Cat、Dog、Tiger,這幾個類中分别有miao、wang、wuuu這幾個方法,那麼從容器中取出元件,調用這幾個方法的時候(注意不是容器初始化時),miao、wang、wuuu這幾個方法執行之前都會輸出hello,執行之後都會輸出world。

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

題目-使用spring為項目裡的所有類的所有方法增加

實作代碼:

題目-使用spring為項目裡的所有類的所有方法增加

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

題目-使用spring為項目裡的所有類的所有方法增加

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();
    }
}
           

結果;

題目-使用spring為項目裡的所有類的所有方法增加