sessionFactory没有被注入。它始终为空

时间:2018-04-07 20:00:14

标签: java spring hibernate session spring-boot

我的服务上的sessionFactory。

    Random random =  new Random();

    int a = random.nextInt(5);
    int b = random.nextInt(5 - a);
    int c = random.nextInt(5 - a - b);
    int d = 5 - (a + b + c);

    System.out.print("a : " + a  +
            "\nb : " + b+
            "\nc : " + c+
            "\nd : " + d +
            "\n\nTotal : " + (a+b+c+d)); \\total will be 5

我从

调用此服务
@Component
public class MyService {    

@Autowired
private SessionFactory sessionFactory;

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

public void persistData(){
  ...

  tx.commit();
  session.close();
}

我的主要课程开始春季训练:

@Component
public class CommandLineApp implements CommandLineRunner {

    @Autowired
    private MyService MyService

    public void run(String... args) throws Exception {
        MyService.persistData();
    }

}

当我调用MyService时,它会收到错误nullPointException。当我调试代码时,我可以看到sessionFactory为null。为什么没有在MyService上注入sessionFactory?

1 个答案:

答案 0 :(得分:1)

这里的问题是SessionFactory bean仍然没有 可用于弹簧容器供您注射。 所以首先你需要引导它。 创建一个@configuration文件 或者将@Configuration添加到您的Main.java并引导您的bean,如下所示

@Configuration
public class HibernateSessionProvider {

  @Bean  // If using hibernate.cfg.xml
  public void getSessionFactory() {
    AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
    ...
    return annotationSessionFactoryBean()
  }

  @Bean  // If using java based config to provide DataSource beans , hibernate config  
  public void getSessionFactory() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    ...
    return localSessionFactoryBean()
  }
}