为什么不调用PostConstruct? [英] Why is PostConstruct not called?

查看:179
本文介绍了为什么不调用PostConstruct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的Java EE应用程序。



我有这样的类:

  import javax.annotation.PostConstruct; 
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@Stateless
public class BlogEntryDao {

EntityManager em;

@PostConstruct
public void initialize(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory(Persistence);
em = emf.createEntityManager();
}

public void addNewEntry(){
Blogentry blogentry = new Blogentry();

blogentry.setTitle(Test);
blogentry.setContent(asdfasfas);

em.persist(blogentry);

}
}

所以我的托管bean调用这个方法。直到这里没有问题。但是,由于初始化方法没有被调用,所以我在 em.persist 中得到一个NPE。



为什么初始化方法不被调用?我在Glassfish服务器上运行这个。



请问。

解决方案

Java EE bean注释(如 @PostConstruct )仅适用于容器管理的bean。如果您自己简单地调用新的BlogEntryDao ,容器将不会拦截创建,并调用 @PostConstruct 方法。



(此外,您最好使用 @PersistenceContext @ PersistenceUnit 而不是在您的 initialize()方法中手动获取 EntityManagerFactory ,而应该为每次调用 addNewEntry()创建一个 EntityManager ,因为它们是短暂的,进行这些更改消除对 initialize()的需要。)


I am working on a simple Java EE application.

I have class like this:

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@Stateless
public class BlogEntryDao {

    EntityManager em;

    @PostConstruct
    public void initialize(){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Persistence");
        em = emf.createEntityManager();
    }

    public void addNewEntry(){
        Blogentry blogentry = new Blogentry();

        blogentry.setTitle("Test");
        blogentry.setContent("asdfasfas");

        em.persist(blogentry);

    }
}

So my managed bean calls this method. Until here no problems. But since the initialize method is not called, I am getting an NPE in em.persist.

Why is the initialize method not being called? I am running this on Glassfish server.

Regards.

解决方案

The Java EE bean annotations such as @PostConstruct only apply to container-managed beans. If you are simply calling new BlogEntryDao yourself, the container isn't going to intercept the creation and call the @PostConstruct method.

(Furthermore, you'd be better off using @PersistenceContext or @PersistenceUnit instead of manually fetching the EntityManagerFactory in your initialize() method, and you should be creating an EntityManager for each call to addNewEntry(), since they're short-lived. Making these changes would eliminate the need for initialize() at all.)

这篇关于为什么不调用PostConstruct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆