The dependency is available on maven central. To include it in your project simply add it to your dependencies:
<dependency>
<groupId>io.github.lumnitzf</groupId>
<artifactId>eager-beans</artifactId>
<version>${eager-beans.version}</version>
</dependency>
To mark a bean as eager initialized simply annotate it as @Eager
.
An eager bean must not have scope @Dependent
.
import javax.enterprise.context.RequestScoped;
import javax.annotation.PostConstruct;
import io.github.lumnitzf.eagerbeans.Eager;
@Eager
@RequestScoped
public class EagerBean {
@PostConstruct
void init() {
System.out.println("Bean initialized");
}
}
In this example, as soon as the request scope is initialized the bean will also be initialized, triggering the @PostConstruct
annotated method.
The @Eager
may also be placed on a stereotype, or even a complete scope.
The initialization will be triggered by calling the toString()
method of the bean.
If this behavior is not desired (e.g. toString triggers other lazy beans) the bean may implement EagerInitializable
.
The initialization will then be triggered by using the no-op method EagerInitializable::triggerInitialization
.
import javax.enterprise.context.RequestScoped;
import javax.annotation.PostConstruct;
import io.github.lumnitzf.eagerbeans.Eager;
import io.github.lumnitzf.eagerbeans.EagerInitializable;
@Eager
@RequestScoped
public class EagerBean implements EagerInitializable {
@PostConstruct
void init() {
System.out.println("Bean initialized");
}
@RequestScoped
public String toString() {
// expensive computation
}
}