Java Reference
In-Depth Information
LISTING 4‐10: (continued)
public class MyLoggingBean {
private Logger logger;
@PostConstruct
public void start(){
logger = Logger.getLogger("MyGlobalLogger");
logger.info("Well, I started first!!!");
}
public void logInfo(String msg){
logger.info(msg);
}
}
Here you can also use the @PostConstruct annotation to test that your bean has been created and
its life cycle has begun. Methods annotated with @PostConstruct are invoked on newly constructed
beans after all dependency injection has been done and before the i rst business method is invoked.
Of course, in real life, you need to use singleton beans inside other beans. Later chapters will focus
more on integration and access of EJB and whether they should be singletons.
The preceding example beans run when the server is started. CacheSingletonBean waits to
run because it depends on MyLoggingBean initialization. The logger output is similar to the
following:
> Well, I started first!!!
> Started!
You r si ng leton bean might depend on the initialization of a sequence of other beans. In this case,
you can specify multiple beans in the @DependsOn . The following singleton bean depends on
MyLoggingBean and MyInitializationBean :
@Startup
@DependsOn({"MyLoggingBean","MyInitializationBean"})
@Singleton
public class CacheSingletonBean {
// Implementation code here.
}
The order in which MyLoggingBean and MyInitializationBean are initialized is determined by
their own @DependsOn annotations. If neither bean explicitly depends on the other, the beans are
initialized by the container in an unspecii ed order.
Managing Concurrency
The most important problem you'll face is concurrency. With the Java EE implementation, you
no longer need to worry about the creation of the bean, but you may still need to be careful about
method access because your singleton will be exposed in a concurrent environment. Java EE, again,
solves this issue with annotations.
 
Search WWH ::




Custom Search