代理类
try {
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
实现InstantiationAwareBeanPostProcessor
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
System.out.println("beanName:"+beanName+"----执行postProcessBeforeInstantiation方法");
if (beanClass == BeforeInstantiation.class){
return new BeforeInstantiation();
}
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
System.out.println("beanName:"+beanName+"----执行postProcessAfterInstantiation方法");
return false;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("beanName:"+beanName+"----执行postProcessBeforeInitialization方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("beanName:"+beanName+"----执行postProcessAfterInitialization方法");
return bean;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
System.out.println("beanName:"+beanName+"----执行postProcessProperties方法");
return pvs;
}
}
public class BeforeInstantiation {
public void doSomeThing(){
System.out.println("执行do some thing....");
}
}
public class MyMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("目标方法执行之前:" + method);
Object o1 = methodProxy.invokeSuper(o, objects);
System.out.println("目标方法执行之后:" + method);
return o1;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beforeInstantiation" class="BeforeInstantiation"></bean>
<bean id="myInstantiationAwareBeanPostProcessor" class="MyInstantiationAwareBeanPostProcessor"></bean>
</beans>
test
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("xxx.xml");
BeforeInstantiation bean = ac.getBean(BeforeInstantiation.class);
bean.doSomeThing();
}
}