Java Reference
In-Depth Information
Listing 12.5. Constructor using dependency injection
Using injection with a constructor gives you another approach for controlling the instanti-
ation of a bean . Only one constructor can be annotated for injection; if multiple con-
structors were annotated, the container would have no idea which one to use. In the case
of the LandingController , the annotation is removed from the member variable
and a parameter is added to the constructor. A default constructor is provided; that's
often required by the container because the container usually wraps the object in a proxy to
support method interceptors.
In the first example you could have easily used the @EJB annotations. The real power of
the @Inject annotation is apparent when you annotate the constructor. This is a more
natural approach—you don't need to use the @PostConstruct annotation to do setup
operations after the bean is created and injection is performed. Using injection with con-
structors enables the beans to behave like regular POJOs—parameters are passed in via the
constructor and the object initializes itself like any other object. You don't have to do in-
jection and then use a callback to initialize the bean.
Up to this point, you've been letting the container instantiate the beans. But there are many
situations where you want to control the creation of a bean and perform cleanup logic when
the bean is to be destroyed. Let's take a look at producer methods.
Search WWH ::




Custom Search