自动装配注释在DAO类中不起作用。使用Spring

时间:2019-03-01 07:04:15

标签: spring spring-mvc spring-jdbc spring-java-config

我试图使用Spring框架5建立一个简单的注册和登录。并且我试图通过实现Java config类来避免xml配置。我还不想使用休眠,因为在我使用简单但高级的休眠之前,我想先学会使其与Spring jdbc一起使用。我试图从属性文件加载数据库凭据。

我提交注册表后得到了这个例外。

我试图使用println方法和记录器显示错误,但是由于某些原因我没有弄清楚,因此没有显示。这是两件事

  1. 无法确切找到创建NullpointerException的内容,因为它说它是嵌套的Exception。我认为是数据库连接导致了此问题,如果我是数据库连接,为什么我没有SQLDriver类找不到异常,我感到困惑。

  2. 为什么我不能显示导致空异常的变量输出,为什么我的记录器实现不显示任何错误详细信息。

我尝试了各种方法来解决它,但是由于无法正常工作而浪费了很长时间。因此,我在这里寻求专家的帮助。

我认为我尝试加载数据库凭据以使数据库连接正常工作的方式进展不顺利,因为数据源仍然为空,我想因此我想知道 如何使用java config类(不是xml方法)从属性文件加载数据库凭据并在DAO中使用它?

database-properties.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tutorstudentdb1
jdbc.user=webadmin
jdbc.pass=Password1

DispatcherConfig类

package com.rabin.tutorstudent.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

    public class DispatcherConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

        @Override
        protected Class<?>[] getRootConfigClasses() {

            return new Class[] {PersistanceConfig.class};
        }

        @Override
        protected Class<?>[] getServletConfigClasses() {

            return new Class[] {SpringConfig.class};
        }

        @Override
        protected String[] getServletMappings() {

            return new String[] {"/"};
        }

    }

PersistanceConfig类

package com.rabin.tutorstudent.config;

import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:database-properties.properties"})
@ComponentScan({"com.rabin.tutorstudent"})
public class PersistanceConfig {
    //env
        @Autowired
        private Environment env;
        @Bean
        public  DataSource dataSource() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
            dataSource.setUrl(env.getProperty("jdbc.url"));
            dataSource.setUsername(env.getProperty("jdbc.user"));
            dataSource.setPassword(env.getProperty("jdbc.pass"));

            return dataSource;
        }
}

SpringConfig类

package com.rabin.tutorstudent.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
//@ComponentScan({"com.rabin.tutorstudent"})
@PropertySource({"classpath:database-properties.properties"})
@ComponentScan(basePackages= "com.rabin.tutorstudent")
public class SpringConfig {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;

    }


}

UserDAOImpl

package com.rabin.tutorstudent.daoimpl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.rabin.tutorstudent.dao.UserDAO;
import com.rabin.tutorstudent.model.User;

public class UserDAOImpl implements UserDAO {
    public final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);

    @Autowired
    private DataSource dataSource;

    /*
    public void setDataSource(DataSource dataSource) {

        this.dataSource = dataSource;
        System.out.print(dataSource);
    }
    */
    public void save(User user)  {
        String query = "insert into user (username, password, firstname, lastname, email, role) values (?,?,?,?,?,?)";
        logger.debug(query);

        Connection con = null;
        logger.debug("Connection Initialization "+con);
        PreparedStatement ps = null;

        try {
            logger.debug("Datasource value=" +dataSource);
            con = dataSource.getConnection();
            logger.info("Connection to db"+con);
            System.out.println("Connection :"+con);


            ps = con.prepareStatement(query);
            //ps.setLong(parameterIndex, x);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getFirstName());
            ps.setString(4, user.getLastName());
            ps.setString(5, user.getEmail());
            ps.setString(6, user.getRole());
            int out = ps.executeUpdate();

            if(out !=0){
                System.out.println("Employee saved with id="+user.getId());
            } else {
                System.out.println("Employee save failed with id="+user.getId());
            }
        } catch (SQLException e) {
            System.out.println("Sql error" +e.getMessage());
        }

    }

    public User getById(Long id) {
        // TODO Auto-generated method stub
        return null;
    }

    public void update(User user) {
        // TODO Auto-generated method stub

    }

    public void deleteById(Long id) {
        // TODO Auto-generated method stub

    }

    public List<User> getAll() {
        // TODO Auto-generated method stub
        return null;
    }

}

UserDAO

package com.rabin.tutorstudent.dao;

import java.util.List;

import com.rabin.tutorstudent.model.User;

public interface UserDAO {

    //Create - insert
    public void save(User user);

    //Read - select
    public User getById(Long id);

    //Update - change
    public void update(User user);
    //Delete - Remove
    public void deleteById(Long id);
    // Get All
    public List<User> getAll();
}

SignUpController

package com.rabin.tutorstudent.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.rabin.tutorstudent.daoimpl.UserDAOImpl;
import com.rabin.tutorstudent.model.User;


@Controller
public class SignUpController {
    public final Logger logger = LoggerFactory.getLogger(SignUpController.class);
    @Autowired
    // sessionFactory;

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String signUp() {
        return "register";

    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView signUpPost(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("firstname") String firstname,
            @RequestParam("lastname") String lastname,
            @RequestParam("email") String email,
            @RequestParam("role") String role) {
        logger.debug("Inside signUpPost method.");
        ModelAndView mv = new ModelAndView();
        logger.info("Model view ="+mv);
        User user = new User(username, password, email, firstname, lastname, role);
        user.setUsername(username);
        user.setPassword(password);
        user.setFirstName(firstname);
        user.setLastName(lastname);
        user.setEmail(email);
        user.setRole(role);
        //dao call
        UserDAOImpl uDAO = new UserDAOImpl();
        //UserDAO uDAO = new UserDAO();

        //User u = new User(username, password, email, firstname, lastname, role);
        //uDAO.insertUser(u);
        uDAO.save(user);
        System.out.println("User Registered..");
        return mv;



    }
}

用户

package com.rabin.tutorstudent.model;

public class User {
private Long id;

    private String username;

    private String password;

    private String email;

    private String firstName;

    private String lastName;

    private String role;

    public User() {
        super();
    }

    public User(Long id, String username, String password, String email, String firstName, String lastName,
            String role) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.role = role;
    }


    public User(String username, String password, String email, String firstName, String lastName, String role) {
        super();
        this.username = username;
        this.password = password;
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.role = role;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }


}

这是我的控制台输出,为我提供了嵌套的NullpointerException。

Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Server version:        Apache Tomcat/8.5.38
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Server built:          Feb 5 2019 11:42:42 UTC
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Server number:         8.5.38.0
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: OS Name:               Windows 10
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: OS Version:            10.0
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Architecture:          amd64
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Java Home:             C:\Program Files\Java\jre1.8.0_152
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: JVM Version:           1.8.0_152-b16
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: JVM Vendor:            Oracle Corporation
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: CATALINA_BASE:         C:\Users\G3\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: CATALINA_HOME:         C:\Users\G3\Downloads\apache-tomcat-8.5.38
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Command line argument: -Dcatalina.base=C:\Users\G3\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Command line argument: -Dcatalina.home=C:\Users\G3\Downloads\apache-tomcat-8.5.38
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Command line argument: -Dwtp.deploy=C:\Users\G3\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\G3\Downloads\apache-tomcat-8.5.38\endorsed
        Feb 28, 2019 5:47:03 PM org.apache.catalina.startup.VersionLoggerListener log
        INFO: Command line argument: -Dfile.encoding=Cp1252
        Feb 28, 2019 5:47:03 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
        INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_152\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_152/bin/server;C:/Program Files/Java/jre1.8.0_152/bin;C:/Program Files/Java/jre1.8.0_152/lib/amd64;C:\Program Files (x86)\Intel\iCLS Client\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Brackets\command;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\xampp\php;C:\ProgramData\ComposerSetup\bin;C:\Users\G3\AppData\Local\Programs\Python\Python37-32\Scripts\;C:\Users\G3\AppData\Local\Programs\Python\Python37-32\;C:\Users\G3\AppData\Local\Microsoft\WindowsApps;C:\Users\G3\AppData\Roaming\Composer\vendor\bin;C:\Users\G3\Desktop;;.]
        Feb 28, 2019 5:47:03 PM org.apache.coyote.AbstractProtocol init
        INFO: Initializing ProtocolHandler ["http-nio-8080"]
        Feb 28, 2019 5:47:04 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
        INFO: Using a shared selector for servlet write/read
        Feb 28, 2019 5:47:04 PM org.apache.coyote.AbstractProtocol init
        INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
        Feb 28, 2019 5:47:04 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
        INFO: Using a shared selector for servlet write/read
        Feb 28, 2019 5:47:04 PM org.apache.catalina.startup.Catalina load
        INFO: Initialization processed in 702 ms
        Feb 28, 2019 5:47:04 PM org.apache.catalina.core.StandardService startInternal
        INFO: Starting service [Catalina]
        Feb 28, 2019 5:47:04 PM org.apache.catalina.core.StandardEngine startInternal
        INFO: Starting Servlet Engine: Apache Tomcat/8.5.38
        SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
        SLF4J: Defaulting to no-operation (NOP) logger implementation
        SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
        Feb 28, 2019 5:47:06 PM org.apache.catalina.core.ApplicationContext log
        INFO: 1 Spring WebApplicationInitializers detected on classpath
        Feb 28, 2019 5:47:06 PM org.apache.jasper.servlet.TldScanner scanJars
        INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
        Feb 28, 2019 5:47:06 PM org.apache.catalina.core.ApplicationContext log
        INFO: Initializing Spring root WebApplicationContext
        Feb 28, 2019 5:47:08 PM org.apache.catalina.core.ApplicationContext log
        INFO: Initializing Spring FrameworkServlet 'dispatcher'
        Feb 28, 2019 5:47:09 PM org.apache.coyote.AbstractProtocol start
        INFO: Starting ProtocolHandler ["http-nio-8080"]
        Feb 28, 2019 5:47:09 PM org.apache.coyote.AbstractProtocol start
        INFO: Starting ProtocolHandler ["ajp-nio-8009"]
        Feb 28, 2019 5:47:09 PM org.apache.catalina.startup.Catalina start
        INFO: Server startup in 5279 ms
        Feb 28, 2019 5:47:40 PM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/tutorstudent] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
        java.lang.NullPointerException
            at com.rabin.tutorstudent.daoimpl.UserDAOImpl.save(UserDAOImpl.java:41)
            at com.rabin.tutorstudent.controller.SignUpController.signUpPost(SignUpController.java:53)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Unknown Source)

在浏览器上输出

HTTP Status 500 – Internal Server Error


Type Exception Report

Message Request processing failed; nested exception is java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:986)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


Root Cause
java.lang.NullPointerException
    com.rabin.tutorstudent.daoimpl.UserDAOImpl.save(UserDAOImpl.java:41)
    com.rabin.tutorstudent.controller.SignUpController.signUpPost(SignUpController.java:53)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

1 个答案:

答案 0 :(得分:1)

问题不在于数据源初始化,它是从属性文件中拾取值,因为在初始化时没有错误,但是,@ Auotwired在DAOImpl中不起作用。可能是因为您没有使用@component注释。 Spring不知道必须在DAOImpl中自动装配data source

此外,为什么不自动为UserDAO中的SignUpController进行布线?您正在拿​​起DI并期望Spring为您自动进行布线。如果您打算自己实例化该对象,则还应该设置数据源。 我建议您参考一些示例以简化此操作。