I’m a regular Spring framework user and I think I know the framework pretty well, but it seems I’m always stumbling upon something useful I didn’t know about.
At Devoxx, I learned that you could express conditional dependencies using Java 8’s new Optional<T>
type.
Note that before Java 8, optional dependencies could be auto-wired using @Autowired(required = false)
, but then you had to check for null.
How good is that? Well, I can think about a million use-cases, but here are some that come out of my mind:
- Prevent usage of infrastructure dependencies, depending on the context.
For example, in a development environment, one wouldn’t need to send metrics to a
MetricRegistry
- Provide defaults when required infrastructure dependencies are not provided e.g. a h2 datasource
- The same could be done in a testing environment.
- etc.
The implementation is very straightforward:
@ContextConfiguration(classes = OptionalConfiguration.class)
public class DependencyPresentTest extends AbstractTestNGSpringContextTests {
@Autowired
private Optional<HelloService> myServiceOptional;
@Test
public void should_return_hello() {
String sayHello = null;
if (myServiceOptional.isPresent()) {
sayHello = myServiceOptional.get().sayHello();
}
assertNotNull(sayHello);
assertEquals(sayHello, "Hello!");
}
}
At this point, not only does the code compile fine, but the dependency is evaluated at compile time.
Either the OptionalConfiguration
contains the HelloService
bean - and the above test succeeds, or it doesn’t - and the test fails.
This pattern is very elegant and I suggest you list it into your bag of available tools.