IoC – a pretty simple example

Before exploring the CDI, let's use a very simple example (I would say, a handmade example) to illustrate what a bean container is.

We will use an application that has TimeService, which simply provides a now() method returning the current LocalDateTime.

Here is what it can look like in terms of code:

public interface TimeService {    LocalDateTime now();}

A trivial implementation will rely on the native now() implementation:

public class TimeServiceImpl implements TimeService {    @Override    public LocalDateTime now() {        return LocalDateTime.now();    }}

But you may also need to be able to switch to a mock (for tests or another customer, for instance):

public class MockTimeService implements TimeService {    @Override    public ...

Get Java EE 8 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.