写几个不同的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();
}
}
结果;