There's two issues with your code:
Problem 1:
CDI does not manage beans created with new
. For the most part you need to @Inject a bean in order for its life cycle to be managed by the container
Problem 2:
For the most part, you cannot inject bean instances into observers of container events. That's because the events are firing as the container is being initialized, aka before it can actually begin managing object life cycles.
You could hook the container initializer observer directly into your Test class. Something like this:
public class SimpleClass {
public void doSomething() {
System.out.println("Consider it done");
}
@PostConstruct
public void initialize() {
System.out.println("Starting");
}
@PreDestroy
public void stop() {
System.out.println("Stopping");
}
}
public class Test {
@Inject
private SimpleClass simple;
public void main(@Observes ContainerInitialized event) {
System.out.println("Starting application");
simple.doSomething();
}
}