我可以使用以下代码使用xml配置从一个java类中的两个bean创建:
<context:component-scan base-package="some.package"/>
<bean id="dependentBean" class="some.package.DependentBean">
<property name="firstBean" ref="firstBean"/>
</bean>
<bean id="firstBean" class="some.package.Handler">
<constructor-arg index="0" ref="service"></constructor-arg>
<property name="defaultUrl" value="url/first"></property>
</bean>
<bean id="secondBean" class="some.package.Handler">
<constructor-arg index="0" ref="service"></constructor-arg>
<property name="defaultUrl" value="url/second"></property>
</bean>
我的目标是将 firstBean 和 secondBean 移动到基于 java 的配置,如下所示:
package some.package;
@Configuration
public class Configuration {
@Bean(name="firstBean")
public Handler firstHandler(Service service){
Handler handler= new Handler(service);
handler.setDefaultTargetUrl("url/first");
return handler;
}
@Bean(name="secondBean")
public Handler secondHandler(Service service){
Handler handler = new Handler(service);
handler.setDefaultTargetUrl("url/second");
return handler;
}
}
但是当上下文开始加载时,spring 会抛出以下异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'firstBean' is defined
尽管如此,它在这种情况下仍然有效:
package some.package;
@Component
public class Filter{
private Handler handler;
@Autowired
public Filter(@Qualifier("secondBean") Handler handler) {
this.handler = handler;
}
}
处理程序实现:
public class Handler {
private Service service;
@Autowired
public Handler(Service service) {
this.service = service;
}
}