自动装配dataSource时出错

时间:2013-12-09 10:03:51

标签: spring-mvc

我收到错误说: 例外

javax.servlet.ServletException: Servlet.init() for servlet spring threw exception
    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:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

根本原因

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.labs.dao.LoginDao com.labs.controllers.LoginController.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\Program Files\Apache Software Foundation\Tomcat 7.0\wtpwebapps\Annotated\WEB-INF\classes\com\labs\dao\LoginDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.labs.dao.LoginDao]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
    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:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

这是我的控制器

@Controller
public class LoginController {
    @Autowired
    private LoginDao loginDao;
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public ModelAndView login(@ModelAttribute User user){
        if(loginDao.login(user))
            return new ModelAndView("success", "user", user);
        return new ModelAndView("failure");
    }
    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
    public LoginDao getLoginDao() {
        return loginDao;
    }

}

和MyDao

@Repository
public class LoginDao {
    @Autowired
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());

    public boolean login(User user){
        String name = jdbcTemplate.queryForObject("select name from users where name=? and password=?",new Object[]{user.getUserName(),user.getPassword()},String.class);
        if(!name.isEmpty())
            return true;
        return false;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public DataSource getDataSource() {
        return dataSource;
    }
}

弹簧配置

<context:annotation-config/>
     <context:component-scan base-package="com.labs"/>

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
        <property name="username" value="postgres"/>
        <property name="password" value="Raju"/>
     </bean>

     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- <property name="viewClass" value=""></property> -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"></property>
     </bean>

1 个答案:

答案 0 :(得分:0)

这一行是问题

private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());

在调用构造函数之前初始化实例变量,在Spring有时间自动装配任何字段之前 。换句话说,dataSourcenullgetDataSource()因此返回null。如果JdbcTemplate参数为DataSource,则null会抛出异常。

而是将代码更改为

private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@Autowired
public LoginDao(DataSource dataSource) {
    this.dataSource = dataSource;
    this.jdbcTemplate =  new JdbcTemplate(this.dataSource);
}