I have faced with the following issue. I am using Weld
implementation of the CDI
.
I have found that if a service is annotated with @ApplicationScoped
then @PostConstruct
section is not invoked until the first usage of the service. Here is a code to reproduce this behaviour:
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.spi.CDI;
public class TestCdi {
public static void main(String[] args) {
try (WeldContainer weldContainer = new Weld().containerId("test").initialize()) {
FooService fooService = CDI.current().select(FooService.class).get();
fooService.test();
System.out.println("Done");
}
}
@ApplicationScoped
public static class FooService {
@PostConstruct
public void init() {
System.out.println("Post construct");
}
public void test() {
System.out.println("test");
}
}
}
So, if fooService.test();
is commented, then FooService.init()
is not invoked. But remove @ApplicationScoped
and it is working again!
This seems strange for me and I can't find and description of such behaviour.
Furthermore, the specification of javax.inject.Provider.get()
says that:
Provides a fully-constructed and injected instance of T.
So, what's the issue? Is it designed so or this is a bug? And what is more important for me: how to bypass this issue? I need my service to be @ApplicationScoped
.
@PostConstruct
method is called? – Lordly