gpt4 book ai didi

java - @Inject 和 @Autowired 不起作用,而使用 setter 注入(inject)则有效

转载 作者:行者123 更新时间:2023-12-01 12:05:23 24 4
gpt4 key购买 nike

我使用了@Autowired数百次,但今天我不明白它,@Autowired@Inject都无法在新的环境中工作我刚刚创建的项目,出现了著名的错误

Invalid property 'jdbcTemplate' of bean class [com.xxx.SomeDAO]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

当我在 SomeDAO 中为 jdbcTemplate 添加 setter 时,它可以工作......

applicationContext.xml:

...
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="com.xxx.SomeDAO" class="com.xxx.SomeDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
...

SomeDAO.java:

import org.springframework.jdbc.core.JdbcTemplate;
import javax.inject.Inject;
//import org.springframework.beans.factory.annotation.Autowired;

public class SomeDAO {

@Inject // Doesn't work
//@Autowired // Doesn't work either
private JdbcTemplate jdbcTemplate;
...

/* Works if I add this setter
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}*/
}

什么可以阻止通过注解进行注入(inject)?谢谢!

最佳答案

当使用您提供的 XML 上下文创建 bean 时,无法使用字段注入(inject)。您的类不属于任何组件扫描,因此注释不会生效。因此,我至少可以看到以下选项:

<强>1。根据您的示例使用 setter 并删除 @Inject

这是自从您准备好代码和 XML 以来最简单的方法。但是,这意味着您的 DAO 必须公开不必要的 setter 方法。

<强>2。使用设置 jdbcTemplate 字段

的构造函数

我认为这是一个更好的选择,但这意味着您需要像这样重写 XML:

<bean id="com.xxx.SomeDAO" class="com.xxx.SomeDAO">
<constructor-arg ref="jdbcTemplate"/>
</bean>

而且,你的构造函数是这样的:

public class SomeDAO {
private final JdbcTemplate jdbcTemplate;

public SomeDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

<强>3。添加组件扫描并使用@Autowired(或@Inject)

我认为,如果您完全想利用 Spring 依赖注入(inject)功能的优点,这是最好的方法。将以下内容添加到您的 XML 上下文中:

<context:component-scan base-package="com.xxx"/>

然后您之前提供的代码应该可以工作。但是,您可能应该考虑避免字段注入(inject)而支持构造函数注入(inject)。 opinions differ on this matter但我发现使用字段注入(inject)时代码更难测试。

构造函数注入(inject)如下所示:

// The component scanner will find this annotation and create 
// the bean (and inject the dependencies)
@Component
public class SomeDAO {
private final JdbcTemplate jdbcTemplate;

@Autowired // enables constructor-injection
public SomeDAO(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

我个人更喜欢替代方案 #3,因为它干净、基于 Java(实际上不需要 XML),这也意味着它重构友好,没有字段魔法> 发生并且基于构造函数的方法使代码可测试并且不会暴露任何不必要的 setter 方法。

了解更多信息的一个很好的起点是优秀的 Spring Documentation 。在那里您可以找到对上述所有内容的精彩解释!

关于java - @Inject 和 @Autowired 不起作用,而使用 setter 注入(inject)则有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com