尽管在xml上下文配置文件中定义,但无法自动装配字段jdbcTemplate

时间:2016-09-18 22:17:13

标签: spring autowired beancreationexception

我在使用@Autowired注释时遇到错误。

UserService类包含带有getter / setter的JdbcTemplate属性。

如果我" wire"来自上下文文件中的该属性:

<bean id="userService" class="org.tuto.service.UserServiceImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

但是使用Autowired我会收到此错误消息。

有人可以通过@Autowired告诉我如何注射而无需配置它。在此先感谢。

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate org.tuto.service.UserServiceImpl.jdbcTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate org.tuto.service.UserServiceImpl.jdbcTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

UserServiceImpl.java:

弹簧servlet.xml中:

package org.tuto.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tuto.mapper.UserMapper;
import org.tuto.model.User;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private JdbcTemplate jdbcTemplate;
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<User> findAllUsers() {
        String SQL = "select * from user";
        UserMapper userMapper = new UserMapper();
        List<User> result = jdbcTemplate.query(SQL, userMapper);
        return result;
    }

    @Override
    public User findById(long id) {
        String SQL = "select * from users where id = ?";
        User result = jdbcTemplate.queryForObject(SQL, new Object[] { id }, new UserMapper());
        return result;
    }
}

0 个答案:

没有答案