Java Lazy initializing CDI bean

Lazy initializing CDI bean

Sometimes, it is better to create a bean instance lazily initialized.
This can be achieved by using Instance<?> injection points.

<p style="text-align: left;">public class someBean {
@Inject
Instance<LazyService> lazyService;</p>
public void doSomething() {
lazyService.get().someMethod();
}
}

There is a change that the instance cannot be instantiated in the Runtime because there is no appropriate bean type available which can be used to inject.
Instance.isUnsatisfied() method can be used to check if the depencendy is satistified:


public class someBean {
@Inject
Instance<LazyService> lazyService;

public void doSomething() {
if (!lazyService.isUnsatistified())
lazyService.get().someMethod();
}
}

If there are more bean candidates, all of them are available in the Instance. In een loop can all of the instances reachted.


public class someBean {
@Inject @Any
Instance<LazyService> lazyService;

public void doSomething() {
for(LazyService lazyService: services) {
if (!lazyService.isUnsatistified())
lazyService.get().someMethod();
}
}
}

A specific bean can be choosen from the available beans


public class someBean {
@Inject
Instance<LazyService> lazyService;

public void doSomething() {
lazyService.select(new AnnotationLiteral()<Type1>{}).get().someMethod();

}
}

@Type1
public class LazyServiceImpl1 implements LazyService{...}


@Type2
public class LazyServiceImpl2 implements LazyService{...}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s