简体   繁体   English

Hibernate 5.x + Spring 5.x,无法自动装配DAOImpl类中的SessionFactory

[英]Hibernate 5.x + Spring 5.x, can't autowire SessionFactory in DAOImpl class

I'm writing a very simplistic crm web app and I've got a problem with autowiring hibernate sessionFactory bean in one of my DAO classes. 我正在编写一个非常简单的crm Web应用程序,并且在我的DAO类之一中自动装配了休眠的sessionFactory bean时遇到了问题。 I've been searching internet for couple days now and I'm quite confused, cause my config seems to mirror those that are said to be working on the net. 我已经在互联网上搜索了几天,我很困惑,因为我的配置似乎反映了据说在网络上工作的那些配置。 In this project I don't use xml's. 在这个项目中,我不使用xml。

web servlet config class 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 config class 春天的配置类

@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();
}

}

hibernate config file 休眠配置文件

@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;
}

}

And I'm trying to autowire sessionFactory in this DAO class, but when I call testMethod to see if sessionFactory have been injected, it throws NullPointerException . 我试图在这个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;
}
}

exception: 例外:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/crm2-project] threw exception [Request processing failed; 严重:路径为[/ crm2-project]的上下文中的Servlet [dispatcher]的Servlet.service()抛出异常[请求处理失败; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.crmproject.dao.CustomerDAOImpl.testMethod(CustomerDAOImpl.java:26) at com.crmproject.controller.CustomerController.listCustomers(CustomerController.java:31) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) 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.i 嵌套异常是java.lang.NullPointerException],其根本原因是com.crmproject.dao.CustomerDAOImpl.testMethod(CustomerDAOImpl.java:26)处com.crmproject.controller.CustomerController.listCustomers(CustomerController.java:31)上的java.lang.NullPointerException )at sun.reflect.NativeMethodAccessorImpl.invoke0(本地方法)at java.lang.reflect处sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(Method.java:498)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java: 136)在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.i上的org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) nvokeHandlerMethod(RequestMappingHandlerAdapter.java:877) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) 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:974) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at o org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)上的nvokeHandlerMethod(RequestMappingHandlerAdapter.java:877)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle( org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)位于org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)位于org.springframework.web位于org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)的.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)位于javax.servlet.http.HttpServlet.service(HttpServlet.java:634) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain)上的javax.servlet.http.HttpServlet.service(HttpServlet.java:741)上的org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) java:231)在o rg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) 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:502) 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:651) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAda org.apache.tomcat.websocket.server处的rg.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)org.apache.catalina.core.ApplicationFilterChain处的WsFilter.doFilter(WsFilter.java:53)。 org.apache.catalina.core上的internalDoFilter(ApplicationFilterChain.java:193)在org.apache上的org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)上的org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)上的.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java :140),位于org.apache.catalina.valves.ErrorReportValve.java:81(位于org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651),位于org.apache.catalina.core。 org.apache.catalina.connector.CoyoteAda上的StandardEngineValve.invoke(StandardEngineValve.java:87) pter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:501) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:501)的pter.service(CoyoteAdapter.java:342)org.apache的org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)的pter.service(CoyoteAdapter.java:342) org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1376)的.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:754)在org.apache.tomcat.util.net.SocketProcessorBase org.apache处的java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)处的.run(SocketProcessorBase.java:49)在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)处的。 tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)在java.lang.Thread.run(Thread.java:748)

Why isn't Spring injecting sessionFactory bean? Spring为什么不注入sessionFactory bean?

edit: Adding controller code per request 编辑:根据请求添加控制器代码

@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());
}

} }

The problem was in my Controller class. 问题出在我的Controller类中。 I tried to create the CustomerDAOImpl object using "new CustomerDAOImpl().testMethod();". 我尝试使用“ new CustomerDAOImpl()。testMethod();”创建CustomerDAOImpl对象。 Spring obviously didn't like it. 春天显然不喜欢它。 I changed it to "@Autowired CustomerDAOImpl customerDAOImpl;" 我将其更改为“ @Autowired CustomerDAOImpl customerDAOImpl;”。 and now it's working, NullPointerException is gone. 现在工作了,NullPointerException消失了。 What a dumb mistake but at the same time, great learning experience. 真是愚蠢的错误,但同时又有很好的学习经验。 Thanks for help! 感谢帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM