Java 如何将新的外部bean添加到Spring容器并自动关联所有依赖项?

Java 如何将新的外部bean添加到Spring容器并自动关联所有依赖项?,java,spring,Java,Spring,假设我有XML配置: <bean id="b" scope="prototype" class="example.component.B"/> <bean id="c" class="example.component.C"/> 我可以创建一个容器,如下所示 ApplicationContext xmlCtx = new ClassPathXmlApplicationContext("context.xml"); 我可以自动连接我的新bean类: xmlCtx.get

假设我有XML配置:

<bean id="b" scope="prototype" class="example.component.B"/>
<bean id="c" class="example.component.C"/>
我可以创建一个容器,如下所示

ApplicationContext xmlCtx = new ClassPathXmlApplicationContext("context.xml");
我可以自动连接我的新bean类:

xmlCtx.getAutowireCapableBeanFactory().autowire(Outcast.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
但是当我运行代码时,我得到一个
null
bean

Outcast outcast = javaCtx.getBeansOfType(Outcast.class).get(0);

你当然会的。您只是自动连接bean,而不是将其作为bean添加到上下文中。但是我想将一个新bean添加到Spring容器中,并将其与容器中的其他bean连接。这不是您已经体验过的方法。你为什么要这么做,通常你不想这么做?有一个
addSingleton
方法可以用来将bean注册为singleton。
Outcast outcast = javaCtx.getBeansOfType(Outcast.class).get(0);