Closed
Description
I am using springboot 2.3.5.RELEASE, have one BeanFactory to load prototype beans implements one interface.
One has a bean to be autowired, another doesn't have the bean.
@Bean
@Scope(value = "prototype")
public DemoInterface getDemoBean( int i) {
switch ( i) {
case 1: return new DemoClassOne();
case 2:
default:
return new DemoClassTwo();
}
}
public class DemoClassOne extends AbstractDemoClass {
@Autowired
Bean2BeAutowired bean2BeAutowired;
}
public class DemoClassTwo extends AbstractDemoClass {
}
If I load BeanOne first, the bean2BeAutowired works fine, but after I load another bean, then generate bean one,
the bean2BeAutowired will be null.
@Test
void contextLoads() {
DemoInterface a1 = ctx.getBean(DemoInterface.class, 1);
System.out.println( a1);
System.out.println( "bean2BeAutowired is ok: "+((DemoClassOne)a1).bean2BeAutowired);
DemoInterface a2 = ctx.getBean( DemoInterface.class, 2);
System.out.println( a2);
DemoInterface a3 = ctx.getBean( DemoInterface.class, 1);
// ctx.getAutowireCapableBeanFactory().autowireBean( a1);
System.out.println( a3);
System.out.println( "bean2BeAutowired is null: "+((DemoClassOne)a3).bean2BeAutowired);
}
The output is:
com.example.demo.DemoClassOne@7561db12
bean2BeAutowired is ok: com.example.demo.Bean2BeAutowired@3301500b
com.example.demo.DemoClassTwo@15deb1dc
com.example.demo.DemoClassOne@6e9c413e
bean2BeAutowired is null: null
It means after I load bean2, the bean1 will not autowired bean2BeAutowired.
The demo code is attached.