gpt4 book ai didi

java - 为什么不使用@Autovired Session Factory? Java hibernate Spring

转载 作者:行者123 更新时间:2023-12-02 11:05:20 26 4
gpt4 key购买 nike

我不明白为什么 bean sessionFactory 没有填写。为什么会发生这种情况?

applicationContext.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,因此他有 null:

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

异常(exception):

 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)

最佳答案

你的 Autowiring 似乎是错误的。您将属性注入(inject)到字段中,但您还有一个打开 session 的构造函数。

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

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

  • 使用基于构造函数的依赖注入(inject)。在球场上做这件事是这不是推荐的方式。
  • 有一个用 @PostConstruct 注释的方法,该方法将是负责启动您的 session 。使用此注释将保证 this 将在之后立即调用已完成的 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();
}

}

关于java - 为什么不使用@Autovired Session Factory? Java hibernate Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com