创建名称为“ userController”的bean时出错:通过字段“ userService”表示的不满意的依赖性

时间:2019-03-16 18:25:00

标签: java xml spring model-view-controller

警告:上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ userController”的bean时出错:通过字段“ userService”表示的不满意的依赖关系;嵌套的异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ userService”的bean时出错:通过字段“ userDao”表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ userDao”的bean时出错:通过方法“ setJdbcTemplate”参数0表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为“ org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate”的合格bean:期望至少有1个可以作为自动装配候选的bean。依赖项注释:{}

   **userController code**

        @Controller
        @RequestMapping("user")
        public class UserController {

        private UserService userService;

        @Autowired
        public void setUserService(UserService userService) {
            this.userService = userService;
        }



        //======== code for user data insert =============
        @GetMapping("/createuser")
        public String showUserform(Model theModel) {
            theModel.addAttribute("user", new User());
            return "userform";
        }

        //@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
        @PostMapping("/saveuser")
        public String saveUser(@ModelAttribute("user") @Valid User user,BindingResult result) {

            if (result.hasErrors()) {
                return "userform";
            }

            user.setAuthority("ROLE_USER");
            user.setEnabled(true);

        return "usercreatesuccess";

        }
   **userservice code**

        @Service("userService")
        public class UserService {

        private UserDao userDao;

        @Autowired
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;`enter code here`
        }



        //======== code for user data insert =============
        public void saveUser(User user) {
            userDao.saveUser(user);
        }



        public boolean exists(String username) {
            return userDao.exists(username);
        }

   **userDao code**


         @Component("userDao")
         public class UserDao {

        private NamedParameterJdbcTemplate jdbcTemplate;

        /*
         * @Autowired private PasswordEncoder passwordEncoder;
         */

        @Autowired
        public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }





         //======== query for user data insert =============
         public boolean saveUser(User user) {

         MapSqlParameterSource params = new MapSqlParameterSource();

            params.addValue("username", user.getUsername());
            params.addValue("password", user.getPassword());
            params.addValue("firstname", user.getFirstname());
            params.addValue("lastname", user.getLastname());
            params.addValue("email", user.getEmail());
            params.addValue("enabled", user.isEnabled());
            params.addValue("authority", user.getAuthority());

            jdbcTemplate.update("insert into users ( username, firstname, lastname, password, email, enabled) values ( :username, :firstname, :lastname, :password, :email, :enabled)", params);
            return jdbcTemplate.update("insert into authorities (username, authority) values (:username, :authority)", params) == 1;

        }

        // query for Duplicate username
        public boolean exists(String username) {
            return jdbcTemplate.queryForObject("select count(*) from users where username=:username", new MapSqlParameterSource("username", username), Integer.class) > 0;
        }
   **[blog-servlet.xml][1]**
        <!-- Add support for component scanning -->
        <context:component-scan base-package="com.spring.mvc.blog.xml" />


        <!-- Add support for conversion, formatting and validation support -->
        <mvc:annotation-driven/>

        <!-- Define Spring MVC view resolver -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="jspViewResolver">
            <property name="prefix" value="/WEB-INF/view/" />
            <property name="suffix" value=".jsp" />
        </bean>

        <!-- Add support for reading web resources: css, images, js, etc ... -->
        <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

        <!-- connection for datasource -->
        <jee:jndi-lookup jndi-name="jdbc/spring" id="dataSource"
            expected-type="javax.sql.DataSource">
        </jee:jndi-lookup>

   **error** 

      [1]: https://i.stack.imgur.com/WZWVj.png

2 个答案:

答案 0 :(得分:2)

您将需要定义JdbcTemplate的Bean

<button onclick="window.open('https://google.com', '_blank')" />

您还需要将注入到jdbcTemplate bean中的DataSource bean:

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
   return new JdbcTemplate(dataSource);
}

如果您不使用Java配置,则为XML配置:

@Bean
public DataSource datasource() {
    DataSource ds = new DataSource();
    ds.setDriverClassName(hostdb_driver);
    ds.setUrl(hostdb_url);
    ds.setUsername(hostdb_user);
    ds.setPassword(hostdb_pass);
    return ds;
}

要注册要注入到jdbctemplate bean中的数据源,您将需要查找所用特定数据库的详细信息。例如,MYSQL与Oracle SQL会有细微的变化。

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

driverClassName和url值对于不同类型的数据库将有所不同。

答案 1 :(得分:1)

ApplicationContext无法初始化userDao bean。

UserDao 依赖于NamedParameterJdbcTemplate

(通过方法'setJdbcTemplate'参数0表示的不满意依赖关系;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate的合格bean)

您应该在Xml或Java配置中创建类型为NamedParameterJdbcTemplate的bean。

@Bean 
public NamedParameterJdbcTemplate namedParameterJdbcTemplate (DataSource datasource){
     return new NamedParameterJdbcTemplate(dataSource);
}

Xml:

<bean id="namedParameterJdbcTemplate"  class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource"/>
</bean>