我有一个 EquityOrder 类,它由 Equity 列表和作为其属性的字符串组成。还定义了一个方法“placeOrder”。我已经自动装配了我的构造函数,并且 Equity 的 bean 已经在我的 XML 文件中定义了。
@Autowired
public EquityOrder(String name, List<Equity> equity) {
this.name = name;
this.equity = equity;
}
public void placeOrder() {
for (Equity eq : equity)
System.out.println("Placing order for " + eq.getSecurityName()
+ "with quantity " + eq.getQuantity());
}
在 xml 中,我有以下场景,这是没有错误的。
<context:annotation-config />
<bean name="testEquity" class="com.sapient.Spring.Equity.Equity">
<property name="symbol" value="MSFT"></property>
<property name="securityName" value="Microsoft"></property>
<property name="type" value="IT"></property>
<property name="quantity" value="100"></property>
</bean>
<bean name="testOtherEquity" class="com.sapient.Spring.Equity.Equity">
<constructor-arg value="GOOG">
</constructor-arg>
<constructor-arg value="Google"></constructor-arg>
<constructor-arg value="IT"></constructor-arg>
<constructor-arg value="100"></constructor-arg>
</bean>
<bean name="testEquityOrder" class="com.sapient.Spring.Equity.EquityOrder">
</bean>
问题 - 当在构造函数中我没有字符串时,项目运行良好。但是如果构造函数中有字符串,它会抛出异常 -
Error creating bean with name 'testEquityOrder' defined in class path resource
[SpringConfig.xml]: Unsatisfied dependency expressed through constructor argument with
index 0 of type [java.lang.String]: : No matching bean of type [java.lang.String] found
for dependency: expected at least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations: {}; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of
type [java.lang.String] found for dependency: expected at least 1 bean which qualifies
as autowire candidate for this dependency. Dependency annotations: {}
这意味着容器正在寻找 String bean,但它不能在那里。如何解决这个问题。一种方法是在 setter 上使用注解。但是如何使用@Autowire
构造函数上的注释来做到这一点?谢谢