BeanFactoryPostProcessor进行bean的注入
BeanFactoryPostProcessor 自定义spring进行注入
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;
@Component
public class MyPostProcess implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
GenericBeanDefinition beanDefinition = (GenericBeanDefinition) beanFactory.getBeanDefinition("userServiceImpl");
//如果需要被注入的bean是接口的实现类,需要将spring默认的jdk代理改为cglib代理
//因为jdk是代理的接口,cglib是根据具体的类来进行代理的
beanDefinition.setBeanClass(UserServiceImpl2.class);
}
}
<aop:aspectj-autoproxy proxy-target-class="true"/>
如果使用默认的jdk代理,会抛出以下异常
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.simon.UserServiceImpl2' available