0

我有一个简单的 POJO 类,我将它注入到很多地方。它没有明确的生产者。我只是这样做@Inject POJO mypojo,而且效果很好。

现在我的问题是我想在注入到其他地方之前初始化 POJO 对象(这涉及从数据源读取)。数据源本身就像@Resource(name = "jdbc/xx") DataSource ds;在 POJO 中一样被注入。现在在我的 POJO 的构造函数中ds,它是 null,它只在构造函数完成后注入。

在创建对象之后和注入之前我可以得到一个钩子,以便我可以在注入之前初始化我的对象吗?

4

1 回答 1

2

This is what the @PostConstruct annotation is for. It is called after your bean is constructed by the CDI container, but before it is actually placed into service. Example:

public class POJO {
    public Pojo() {
        super();
    }

    @PostConstruct
    protected void initialize() {
        // initialization code here
    }
}

Documentation: http://docs.oracle.com/javaee/6/api/javax/annotation/PostConstruct.html

于 2012-12-27T19:50:30.797 回答