gpt4 book ai didi

java - Autowiring 时 JDBCTemplate 为 null

转载 作者:行者123 更新时间:2023-11-30 08:34:10 24 4
gpt4 key购买 nike

我知道这个问题之前被问过很多次,但典型的答案是如果你用 new 创建对象,那么 Spring 不知道它,因此不能进行注入(inject)。在这种情况下,我不明白为什么会这样,因为我在 Spring 中实例化了我的类,但我对 JDBCTemplate 的调用为空。

我在这里犯了什么明显的错误?

public class UserDAOImpl implements UserDAO
{
@Autowired
private JdbcTemplate template;

@Autowired
private PlatformTransactionManager manager;

@Override
public List<User> getUsers()
{
List<User> users = template.query("SELECT * FROM USER", new UserRowMapper());
return users;
}

@Override
public boolean addUser(User user)
{
if (user == null)
{
throw new IllegalArgumentException("Unable to add null user");
}

return true;
}

}


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="url"
value="jdbc:jtds:sqlserver://...;integrated security=false" />
<property name="username" value="..." />
<property name="password" value="..." />
</bean>

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

<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<bean class="com.rest.dao.UserDAOImpl" />

最佳答案

您要么必须在 bean 定义中添加对 JdbcTemplate 的引用,要么添加标签 <context:annotation-config/>在您的 XML 配置中启用注释。

关于java - Autowiring 时 JDBCTemplate 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39014000/

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