spring ioc 泛型保留
spring ioc 泛型保留
在上一篇中,说到spring中并不能自动注入泛型,如何生成泛型类型已经讲的很清楚了,在本篇着重讲在spring中如何自动注入。
环境
这里所有代码基于如下环境,如有出入请参考当前环境。
java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)
implementation 'org.aspectj:aspectjweaver:1.9.2'
implementation "org.springframework:spring-context:5.1.9.RELEASE"
implementation 'org.javassist:javassist:3.25.0-GA'
方法一
通过实现org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
和org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
自定义bean泛型的注入
MainConfig.java
@Configuration
public class MainConfig
{
@Bean
public static MyBeanFactoryPostProcessor newMyBeanFactoryPostProcessor()
{
return new MyBeanFactoryPostProcessor();
}
....
MyBeanFactoryPostProcessor.java
public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor
{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
System.out.println("beanFactory=" + beanFactory);
beanFactory.addBeanPostProcessor(new MyBeanPostProcessor(beanFactory));
}
...
MyBeanPostProcessor.java
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor
{
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException
{
// System.out.println("创建类:" + beanClass);
List<Field> fields = new ArrayList<>();
for (Field field : beanClass.getDeclaredFields())
{
if (field.getAnnotation(Autowired.class) != null && MyProvider.class.isAssignableFrom(field.getType()))
{
Type type = field.getGenericType();
if (type != null && type instanceof ParameterizedType)
{
fields.add(field);
}
}
}
if (!fields.isEmpty())
{
//创建bean,请参考上一篇文章
....
}
return null;
}
...
输出结果如下:
beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory@51081592: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,main,mainConfig,baseProvider,myAspect,testService,testService2,newMyBeanFactoryPostProcessor,newBeanConfig,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy
service=test.spring.service.TestService2@1817d444
superclass=test.spring.provider.MyProvider<test.spring.model.User>
userProviderFieldType=[]
ResolvableType=test.spring.service.TestService2