Hibernate 5.x + Spring 5.x无法自动连接DAOImpl类中的SessionFactory

时间:2018-06-23 12:48:41

标签: java spring hibernate autowired sessionfactory

我正在编写一个非常简单的crm Web应用程序,并且在我的一个DAO类中自动装配了一个休眠sessionFactory bean存在问题。我已经在互联网上搜索了几天,我很困惑,因为我的配置似乎反映了据说在网络上工作的那些配置。在此项目中,我不使用xml。

Web servlet配置类

public class WebServletConfig implements WebApplicationInitializer
{

@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
    AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
    webContext.register(SpringConfig.class);
    webContext.setServletContext(servletContext);
    ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(webContext));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}

spring配置类

@Configuration
@EnableWebMvc
@ComponentScan("com.crmproject")
public class SpringConfig implements WebMvcConfigurer 
{

@Bean
public ViewResolver viewResolver()
{
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

@Bean
public MessageSource messageSource()
{
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("resources/messages");

    return messageSource;
}

public void configureDefaultSevletHandling(DefaultServletHandlerConfigurer configurer)
{
    configurer.enable();
}

}

休眠配置文件

@Configuration
public class HibernateConfig
{

@Bean
public LocalSessionFactoryBean sessionFactory()
{
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan("com.crmproject.entity");
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
}

@Bean
public DataSource dataSource()
{
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC");
    dataSource.setUsername("hbstudent");
    dataSource.setPassword("hbstudent");

    return dataSource;
}

private final Properties hibernateProperties()
{
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");

    return hibernateProperties;
}

}

我正在尝试在此DAO类中自动连接sessionFactory,但是当我调用testMethod来查看是否已注入sessionFactory时,它将抛出NullPointerException

@Repository
public class CustomerDAOImpl implements CustomerDAO
{

@Autowired
private SessionFactory sessionFactory;


public void setSessionFactory(SessionFactory sessionFactory)
{
    this.sessionFactory = sessionFactory;
}

public void testMethod()
{
    System.out.println(sessionFactory.toString());
}

public CustomerDAOImpl()
{
    System.out.println("in CustomerDAOImpl constructor");
}

public List<Customer> getCustomers()
{
    return null;
}

public Integer saveCustomer(Customer customer)
{
    return null;
}

public Customer getCustomer(Integer id)
{
    return null;
}

public boolean updateCustomer(Integer id, Customer customer)
{
    return false;
}

public boolean deleteCustomer(Integer id)
{
    return false;
}
}

例外:

  

严重:Servlet [dispatcher]中的Servlet.service()   路径[/ crm2-project]抛出异常[请求处理失败;   嵌套异常是java.lang.NullPointerException],其根本原因是   java.lang.NullPointerException在   com.crmproject.dao.CustomerDAOImpl.testMethod(CustomerDAOImpl.java:26)     在   com.crmproject.controller.CustomerController.listCustomers(CustomerController.java:31)     在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)在   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:877)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)     在   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:974)     在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:634)在   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:741)处   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)     在   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:501)     在   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)     在   org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:754)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1376)     在   org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)     在   java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:748)

为什么Spring不注入sessionFactory bean?

编辑: 根据请求添加控制器代码

@Controller
@RequestMapping("/customer")
public class CustomerController
{

@RequestMapping("/customerAddForm")
public String showAddCustomerForm(Model model)
{
    model.addAttribute("customer", new Customer());
    System.out.println("Inside showAddCustomerForm method");
    return "customer-add-form";
}

@RequestMapping("/list")
public String listCustomers(Model model)
{
    List<Customer> customers = new ArrayList<>();
    new CustomerDAOImpl().testMethod();
    model.addAllAttributes(customers);

    return "list-customers";
}

@RequestMapping("/proccessAddForm")
public void proccessAddForm(@ModelAttribute("customer")Customer customer)
{
    System.out.println("Inside proccessAddForm method, customer: " + customer.toString());
}

}

1 个答案:

答案 0 :(得分:0)

问题出在我的Controller类中。我尝试使用“ new CustomerDAOImpl()。testMethod();”创建CustomerDAOImpl对象。春天显然不喜欢它。我将其更改为 “ @Autowired CustomerDAOImpl customerDAOImpl;“,现在可以正常使用了,NullPointerException消失了。这是一个愚蠢的错误,但同时,您也获得了很好的学习经验。感谢您的帮助!