문제

I have a simple POJO class that I inject in to many places. There is no explicit Producer for it. I just do @Inject POJO mypojo and it works great.

Now my problem is that I want to initialize the POJO object(which involves reading from a datasource) before its injected to other places. The datasource itself is injected as @Resource(name = "jdbc/xx") DataSource ds; within the POJO. Now in the constructor of my POJO, the ds is null, its only injected after the constructor is complete.

Is there a hook I can get after creating of the object and before injection so I can initialize my object before injection?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top