有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么不@Autovired会话工厂?Java Hibernate Spring

我不明白为什么bean sessionFactory没有填写。为什么会这样

应用程序上下文。xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

      <context:component-scan base-package="config"/>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

声明@Bean sessionFactory的AppConfiguration:

@Configuration
@ComponentScan({"controllers","model","dao","service"})
public class AppConfiguration {

    @Bean
    LocalSessionFactoryBean sessionFactory(){
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setPackagesToScan(new String[]{"model"});
        sessionFactory.setDataSource(datasource());
        return sessionFactory;
    }

    @Bean
    JdbcTemplate jdbcTemplate(){return new JdbcTemplate(datasource());}

    @Bean
    public DataSource datasource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/quizzes");
        dataSource.setUsername("root");
        dataSource.setPassword("dbpass");
        return dataSource;
    }

    @Bean
    HibernateTransactionManager transactionManager(@Autowired SessionFactory sessionFactory){
        HibernateTransactionManager manager= new HibernateTransactionManager();
        manager.setDataSource(datasource());
        manager.setSessionFactory(sessionFactory);
        return manager;
    }


}

使用bean sessionFactory的类。他不是@Autowired,因此他有空:

@Service
public class AnswerDAOReal extends EntityDAO<Answer, Integer> {
    @Autowired SessionFactory sessionFactory;

    public AnswerDAOReal() {
        session=sessionFactory.openSession();
    }
}

抽象类EntityDAO-它是类的父类,例如:AnswerDAOReal、UserDAOReal。。。XxxDAOReal

abstract class EntityDAO<T, Id extends Serializable> {//Wnen: T- is type of Entity, iD- Type of ID// and DAOEntity- inheritor type of DAOEntity
     SessionFactory sessionFactory;
     Session session;

     EntityDAO(){}

    public void persist(T entity) {
        Transaction transaction = session.beginTransaction();
        session.persist(entity);
        session.flush();
        transaction.commit();
    }

    public void update(T entity) {
        Transaction transaction = session.beginTransaction();
        session.update(entity);
        session.flush();
        transaction.commit();
    }

    public T findById(Id id) {
        Transaction transaction = session.beginTransaction();
        T entity= (T) session.get(getGenericType(),id);
        session.flush();
        transaction.commit();
        return  entity;
    }

    public void delete(Id id) {
        Transaction transaction = session.beginTransaction();
        T entity = (T) findById(id);
        session.delete(entity);
        session.flush();
        transaction.commit();
    }

    public List<T> findAll() {
        Transaction transaction = session.beginTransaction();
        List<T> collection = session.createQuery("from "+getGenericType().getSimpleName()).list();
        session.flush();
        transaction.commit();
        return collection;
    }
    public void deleteAll() {
        Transaction transaction = session.beginTransaction();
        List<T> entityList = findAll();
        for (T entity : entityList) {
            session.delete(entity);
        }
        session.flush();
        transaction.commit();
    }


    public Class getGenericType(){
        Class type= (Class) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        return type;
    }
}

例外情况:

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDAOReal'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOReal' defined in file [C:\JProjects\Hillel\SpringQuiz\out\artifacts\Servlet1_war_exploded\WEB-INF\classes\dao\UserDAOReal.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [dao.UserDAOReal]: Constructor threw exception; nested exception is java.lang.NullPointerException

    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDAOReal'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOReal' defined in file [C:\JProjects\Hillel\SpringQuiz\out\artifacts\Servlet1_war_exploded\WEB-INF\classes\dao\UserDAOReal.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [dao.UserDAOReal]: Constructor threw exception; nested exception is java.lang.NullPointerException
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOReal' defined in file [C:\JProjects\Hillel\SpringQuiz\out\artifacts\Servlet1_war_exploded\WEB-INF\classes\dao\UserDAOReal.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [dao.UserDAOReal]: Constructor threw exception; nested exception is java.lang.NullPointerException
    Caused by: java.lang.NullPointerException
        at dao.UserDAOReal.<init>(UserDAOReal.java:16)

共 (1) 个答案

  1. # 1 楼答案

    你的自动接线好像有问题。在字段中注入属性,但也有一个打开会话的构造函数

    首先,我建议避免在字段本身上注入属性,我强烈建议使用构造函数注入。其次,在AnswerDAOReal示例中session属性的声明在哪里

    考虑到这些,我建议如下:

    • 使用基于构造函数的依赖项注入。在球场上做这件事是很困难的 不是推荐的方式
    • 使用@PostConstruct注释一个方法,该方法将 负责会议的开始。使用此注释将 保证在 完成的bean的初始化

    这方面的一个例子是:

    @Service
    public class AnswerDAOReal extends EntityDAO<Answer, Integer> {
    
        private final SessionFactory sessionFactory;
        private Session session;
    
        @Autowired
        public AnswerDAOReal(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
        @PostConstruct
        private void openSession() {
            this.session = sessionFactory.openSession();
        }
    
    }