在构建此代码时,即使正确添加了注释,我也无法为DAO类创建错误bean

警告:上下文初始化期间遇到异常-取消刷新尝试:
org.springframework.beans.factory.BeanCreationException:创建名称为'bankDaoImpl'的bean时出错
在文件[C:\ Users \ saivi \ eclipse-
[workspace \ bank \ target \ classes \ com \ bank \ dao \ BankDaoImpl.class]:实例化Bean失败;嵌套的
异常是org.springframework.beans.BeanInstantiationException:无法实例化
[com.bank.dao.BankDaoImpl]:构造函数抛出异常;嵌套异常为
java.lang.NullPointerException
2019年11月28日9:50:45 org.springframework.web.context.ContextLoader initWebApplicationContext
严重:上下文初始化失败
org.springframework.beans.factory.BeanCreationException:创建名称为'bankDaoImpl'的bean时出错
在文件[C:\ Users \ saivi \ eclipse-
[workspace \ bank \ target \ classes \ com \ bank \ dao \ BankDaoImpl.class]:实例化Bean失败;嵌套的
异常是org.springframework.beans.BeanInstantiationException:无法实例化
[com.bank.dao.BankDaoImpl]:构造函数抛出异常;嵌套异常为
java.lang.NullPointerException

AppConfig.java

包com.bank.config;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.hibernate.cfg.Environment.*;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.bank.dao"),
      @ComponentScan("com.bank.service") })
public class AppConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

      Properties props = new Properties();
      // Setting JDBC properties
      props.put(DRIVER, env.getProperty("mysql.driver"));
      props.put(URL, env.getProperty("mysql.url"));
      props.put(USER, env.getProperty("mysql.user"));
      props.put(PASS, env.getProperty("mysql.password"));

      // Setting Hibernate properties
      props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
      props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));

      // Setting C3P0 properties
      props.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
      props.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
      props.put(C3P0_ACQUIRE_INCREMENT,
            env.getProperty("hibernate.c3p0.acquire_increment"));
      props.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
      props.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setPackagesToScan("com.bank.model");

      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}


MyWebAppInitializer.java

package com.bank.config;

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

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

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

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

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

    @Override
    protected String[] getServletMappings() {

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

}



WebConfig.java

package com.bank.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.bank.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {

}



Bank.java

package com.bank.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="Bank")
public class Bank {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    private String name;
    private Integer balance;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getBalance() {
        return balance;
    }
    public void setBalance(Integer balance) {
        this.balance = balance;
    }
}




BankDaoImpl.java

package com.bank.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.bank.model.Bank;

@Repository
public class BankDaoImpl implements BankDao{

    @Autowired
    private SessionFactory sessionFactory;
    Session s=sessionFactory.getCurrentSession();


    @Override
    public long save(Bank bank) {
        s.save(bank);
        return bank.getId();
    }
    @Override
    public Bank get(long id) {
        return s.get(Bank.class, id);
    }


    @Override
    public void delete(long id) {
        Bank b=s.byId(Bank.class).load(id);
        s.delete(b);

    }

}



BankService.java

package com.bank.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bank.dao.BankDao;
import com.bank.model.Bank;

@Service
@Transactional(readOnly=true)
public class BankServiceImpl implements BankService {

    @Autowired
    private BankDao bankDao;

    @Transactional
    @Override
    public long save(Bank bank) {
        return bankDao.save(bank);
    }

    @Override
    public Bank get(long id) {
        return bankDao.get(id);
    }

    @Override
    public void delete(long id) {
        bankDao.delete(id);

    }

}



pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bank</groupId>
  <artifactId>bank</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

    <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>

  <dependencies>
    <!-- Spring MVC Dependency -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>
    <!-- Spring ORM -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>
    <!-- Hibernate ORM -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.11.Final</version>
    </dependency>
    <!-- Hibernate-C3P0 Integration -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
      <version>5.2.11.Final</version>
    </dependency>
    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Jackson API for JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>
    <!-- Servlet Dependency -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <!-- Embedded Apache Tomcat required for testing web application -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

最佳答案

代码示例Session s=sessionFactory.getCurrentSession();BankDaoImpl的以下行将导致NullPointerException,因为SessionFactory对象尚未进行自动装配,并且您已经在尝试调用其方法。

尝试将行替换为该类中的每个方法。因此,例如,您的BankDaoImpl#save方法将如下所示:

public class BankDaoImpl {

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public long save(Bank bank) {
        Session s = sessionFactory.getCurrentSession();
        s.save(bank);
        return bank.getId();
    }
    ...
}


尝试对sessionFactory类中使用BankDaoImpl的所有其他方法执行上述操作。

08-26 00:52