无法自动连接String类型的bean



我有一个定义如下的bean,我想将其自动连接到Spring上下文文件中定义为bean的class。但它不起作用,奇怪的是,同一类中自动连接的其他对象bean类型都是正确自动连接的。Bean到Autowire如下所示:-

  <bean id="stringToAutowire" class="java.lang.String">
      <constructor-arg value="true" />
  </bean>

类,它要被自动连接的位置是:-我试过用@Component注释它。但没有成功。

public class AService { 
  @Autowired 
  private BDao bDao; 
  @Autowired 
  private String stringToAutowire; 
   ........
 }

上下文文件为:-

<context:annotation-config/>
<context:component-scan base-package ="PKG "/>
<bean id="aService" class="AService"/>
<bean id="bDao" class="BDao"/>
<bean id="stringToAutowire" class="java.lang.String">
  <constructor-arg value="true" />
</bean>

在Spring文档中:

  • http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-自动连线异常

有这样一段文字:"你不能自动连接所谓的简单属性,如基元、字符串和类(以及这些简单属性的数组)。这个限制是由设计的。"

我还没有找到在这种情况下会发生什么的确切说明。根据我的经验,字符串属性的Autowire是不可靠的。有时有效,有时无效。因此,我建议避免字符串值的自动连接。

在您的案例中,您同时使用Autowire和构造函数arg。它们是独立的机制。只需要一个。

  1. 放弃字符串的Autowire
  2. 向AService添加一个构造函数,该构造函数将一个要分配给"stringToAutowire"的字符串作为第一个参数。"构造函数arg"将指定为此构造函数参数传递的内容

尝试使用以下内容:

@Autowired
@Qualifier("stringToAutowire")
private String someString;

您不能自动连接简单属性,如基元、字符串和类(以及此类简单属性的数组),并且属性和构造函数arg设置中的显式依赖项始终覆盖自动连接。

因此,从字符串ToAutowire中删除@Autowired注释,并与属性一起使用。

最新更新