org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为'loginController'的bean时出错

时间:2018-12-06 09:21:53

标签: java spring

我是Spring的新手,我尝试制作一个学习应用程序,但是在自动装配中遇到了问题,正在添加代码。我正在做弹簧靴。

登录控制器:

            package com.cloudnexus.spring.controller;

            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;

            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.stereotype.Controller;
            import org.springframework.web.bind.annotation.ModelAttribute;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RequestMethod;
            import org.springframework.web.servlet.ModelAndView;

            import com.cloudnexus.spring.model.Login;
            import com.cloudnexus.spring.model.User;
            import com.cloudnexus.spring.service.UserService;

            @Controller
            public class LoginController {
                @Autowired
                  UserService userService;

                @RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
                  public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
                  @ModelAttribute("login") Login login) {
                    ModelAndView mav = null;
                    User user = userService.validateUser(login);
                    if (null != user) {
                    mav = new ModelAndView("welcome");
                    mav.addObject("firstname", user.getUsername());
                    } else {
                    mav = new ModelAndView("login");
                    mav.addObject("message", "Username or Password is wrong!!");
                    }
                    return mav;
                  }

            }

            ////

登录POJO:

        package com.cloudnexus.spring.model;

        public class Login {

            private String username;
            private String password;
            public String getUsername() {
                return username;
            }
            public void setUsername(String username) {
                this.username = username;
            }
            public String getPassword() {
                return password;
            }
            public void setPassword(String password) {
                this.password = password;
            }



        }

用户Pojo:

        package com.cloudnexus.spring.model;

        public class User {

            private String username;
            private String password;
            private int IsActive;
            public String getUsername() {
                return username;
            }
            public void setUsername(String username) {
                this.username = username;
            }
            public String getPassword() {
                return password;
            }
            public void setPassword(String password) {
                this.password = password;
            }
            public int getIsActive() {
                return IsActive;
            }
            public void setIsActive(int isActive) {
                IsActive = isActive;
            }

        }

UserDao:

    package com.cloudnexus.spring.dao;

    import com.cloudnexus.spring.model.Login;
    import com.cloudnexus.spring.model.User;

    public interface UserDao {
        User validateUser(Login login);

    }

UserDaoImpl

    package com.cloudnexus.spring.dao;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.List;

    import javax.sql.DataSource;
    import com.cloudnexus.spring.model.Login;
    import com.cloudnexus.spring.model.User;

    public class UserDaoImpl implements UserDao{


        @Autowired
          DataSource datasource;
          @Autowired
          JdbcTemplate jdbcTemplate;
        public User validateUser(Login login) {
            String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
            + "'";
            List<User> users = jdbcTemplate.query(sql, new UserMapper());
            return users.size() > 0 ? users.get(0) : null;
        }

    }


    class UserMapper implements RowMapper<User> {
          public User mapRow(ResultSet rs, int arg1) throws SQLException {
            User user = new User();
            user.setUsername(rs.getString("Name"));
            user.setPassword(rs.getString("Password"));
            user.setIsActive(rs.getInt("IsActive"));

            return user;
          }
        }

UserService:

    package com.cloudnexus.spring.service;

    import com.cloudnexus.spring.model.Login;
    import com.cloudnexus.spring.model.User;

    public interface UserService {
        User validateUser(Login login);

    }

UserServiceImpl

    package com.cloudnexus.spring.service;

    import org.springframework.beans.factory.annotation.Autowired;

    import com.cloudnexus.spring.dao.UserDao;
    import com.cloudnexus.spring.model.Login;
    import com.cloudnexus.spring.model.User;

    public class UserServiceImpl implements UserService{
         @Autowired
          public UserDao userDao;
        public User validateUser(Login login) {
            return userDao.validateUser(login);
        }

    }

spring bean配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

     <context:component-scan base-package="com.cloudnexus.spring" />
        <context:annotation-config />
        <bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
            <property name="userService" ref="userService"></property>
        </bean>

        <bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

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

        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
            <property name="url" value=";DatabaseName=" />
            <property name="username" value="" />
            <property name="password" value="" />
        </bean>

    </beans>
  1. @自动连线到LoginBean loginBean;
  2. 在Controller类中创建了LoginBean的getter设置程序,并自动装配了设置程序;
  3. 创建了Controller的构造函数并自动连接,如上面的代码所示;

    以下是我得到的错误:

    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'userService': Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao': Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in ServletContext resource [/WEB-INF/springBeanConfiguration.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [com.cloudnexus.spring.dao.UserDaoImpl]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    

    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:306) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:603) org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:312) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624) java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

您的jdbcTemplate bean需要一个名为datasource的bean,就像您在此处进行设置(在 ref=... 部分:

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

但是您的datasource bean不存在。原因是因为您已在 dataSource

中将其定义为bean id="dataSource"(注意大写的“ S”)
  <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
        <property name="url" value=";DatabaseName=" />
        <property name="username" value="" />
        <property name="password" value="" />
    </bean>

因此将其更改为“数据源”,例如 bean id="datasource" 或将jdbcTemplate中的引用更改为 ref="dataSource"

<property name="url" value=";DatabaseName=" />看起来也不正确,我想您在这里错过了正确的value";DatabaseName="看起来错误或不完整。

更新

由于您使用的是xml spring配置,因此@AutowiredUserDaoImpl类中的UserServiceImpl注释是不必要的。但是,xml配置要求存在等效的getter / setter。因此,将您的代码更改为:

在您的UserDaoImpl中,您根本不需要dataSource bean,因此我们将其删除。

public class UserDaoImpl implements UserDao{

    JdbcTemplate jdbcTemplate;

    public User validateUser(Login login) {
        String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()
                + "'";
        List<User> users = jdbcTemplate.query(sql, new UserMapper());
        return users.size() > 0 ? users.get(0) : null;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

但是您确实需要jdbcTemplate bean,并且在xml定义中没有设置它,因此也将spring xml文件更新为:

<bean name="userDao" class="com.cloudnexus.spring.dao.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

public class UserServiceImpl implements UserService{

    private UserDao userDao;

    public User validateUser(Login login) {
        return userDao.validateUser(login);
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

此外,spring xml配置文件中还有另一个错误。在userService bean定义中,您将其再次设置为属性:

<property name="userService" ref="userService"></property>

这是错误的,您应该在此处设置userDao。更新为:

<bean id="userService" class="com.cloudnexus.spring.service.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
 </bean>