当前位置: 首页 > 知识库问答 >
问题:

Hibernate5。xSpring5。x、 无法在DAOImpl类中自动连接SessionFactory

云和硕
2023-03-14

我正在编写一个非常简单的crm网络应用程序,我在我的一个DAO类中自动装配hibernate essionFactory 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();
}

}

Hibernate配置文件

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

例外情况:

SEVERE: Sorg.springframework.web.method.support.()为servlet[调度程序]在上下文中的路径[/crm2-project]抛出异常[请求处理失败;嵌套异常是ethod.doNullPointerException]与根本原因ethod.java:209NullPointerException在org.springframework.web.method.support.CustomerDAOIethod.invoke方法(CustomerDAOIethod.java:136)在org.springframework.web.servlet.mvc.method.annotation.CustomerCethod.invoke客户(CustomerCethod.java:102)在org.springframework.web.servlet.mvc.method.annotation.NativeMachodAccessorIdapter.invoke0(Native method)在sun.reflect.NativeMachodAccessorImpl.invoke(NativeMEodAccessorImpl.java:62)在sun.reflect.在java.lang.reflect.Method.invoke(Method.java:498)在ervlet.serviceInvocableHandlerMjava.lang.Invoke(InvocableHandlerMjava.lang.)在com.crmproject.dao.InvocableHandlerMmpl.testForRequest(InvocableHandlerMmpl.java:26)在com.crmproject.controller.ServletInvocableHandlerMontroller.listAndHandle(ServletInvocableHandlerMontroller.java:31)在sun.reflect.Request estMappingHandlerAmpl.invokeHandlermethodFrameworkServlet. service(FrameworkServlet. java: 851)位于javax. servlet. http。HttpServlet. service(HttpServlet. java: 741)位于org. apache. catalina. core。org. apache. catalina. core处的Application ationFilterChain. interalDoFilter(Application ationFilterChain. java: 231)。org. apache. tomcat. websocket. server处的Application ationFilterChain. doFilter(Application ationFilterChain. java: 166)。org. apache. catalina. core处的WsFilter. doFilter(WsFilter. java: 53)。org. apache. catalina. core处的Application ationFilterChain. java: 193。org. apache. catalina. core处的Application ationFilterChain. doFilter(Application ationFilterChain. java: 166)。标准WtaskThread$WrappingRunnable. run(TaskThread. java: 61)在java. lang. Thread. run(Thread. java: 748)

为什么Spring没有注入essionFactory 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个答案

索梓
2023-03-14

问题出在我的控制器类中。我尝试使用“new CustomerDAOImpl().testMethod();”创建CustomerDAOImpl对象。斯普林显然不喜欢它。我将其更改为“@Autowired CustomerDAOImpl CustomerDAOImpl;”现在它开始工作了,NullPointerException消失了。这是一个多么愚蠢的错误,但同时也是一次伟大的学习经历。谢谢你的帮助!

 类似资料:
  • 我有一个使用SpringMVC和SpringBoot的项目,我使用IntelliJ。我的项目如下: 我用注释服务实现。 我用以下内容注释了配置文件 在控制器中,我向服务注入 在测试类中,我使用相同的注释注入相同的服务: 我用以下方法注释测试类: 在控制器中,注入工作正常,但是在测试类中,IntelliJ说: 无法自动连线。找不到WelcomeService类型的beans。 当我运行测试时,它是有

  • 我正在尝试为我的dao类自带一个sessionfactory,但它不起作用 这也是我的服务班 请在这方面提供一点帮助。我已经浪费了一整天的时间来寻找解决办法。提前致谢

  • 我想尝试嵌入式数据库测试我的DAO对象在spring应用程序。 在应用程序上下文中,我有以下标记: 我的JUnit测试类需要使用这个bean: 一切正常(创建了“DataSourceEmbedded”bean),但当我试图在PartnerDAOTest类中自动调用它们时,spring抛出了以下异常: testSavePartner(Sandbox.PartnerDaoTest):创建名为“Sand

  • 我正在学习将activiti与spring boot结合使用,但我遇到了一些错误,并且搜索了太多关于使用spring boot和java的acitiviti稳定版本的信息 我正在使用java 8和tomcat 8.0.3 我更改了这么多版本的spring和jdk,检查了这么多样本,没有发现任何问题,我只有一个控制器类和spring主类,当我运行项目时,得到了以下错误: 这是我的RestContro

  • 我正在尝试创建一个Spring Boot测试类,它应该创建Spring上下文,并自动连接服务类以供我测试。 这就是我得到的错误: 原因:org。springframework。豆。工厂NoSuchBeanDefinitionException:没有“com”类型的合格bean。目瞪口呆。戈布斯。基础服务FileImportService'可用:至少需要1个符合autowire候选资格的bean。依

  • 我正在开发一个spring boot应用程序,我遇到了一个问题。我正在尝试注入一个@Repository注释接口,但它似乎根本不起作用。我收到这个错误 实体类: 存储库接口: 控制器: