What’s Missing from Mastering Spring 5.0

Mastering Spring 5.0 book cover
Mastering Spring 5.0 book cover from Amazon.com

Chapter Dependency Injection

Now that Java 9 and Spring Framework 5.0 have been released and end-of-year is just around the corner I thought I’ll keep my knowledge up-to-date and read Mastering Spring 5.0 from Packt Publishing. Based on the first two chapters it seems to be giving a good overview of the framework in an easy to follow fashion. However, after reading the 2nd chapter I could not resist writing a post about what I believe is missing from it. Despite the book targeting experienced developers when it discusses IoC – Inversion of Control, it fails to mention two advanced but very important features I’ll now share with you.

Defining beans within configuration classes

When the book compares XML configuration with annotations it states that “Classes using annotations are no longer simple POJOs because they are using framework-specific annotations.” Example:

@Service
public class UserService {
  @Autowired
  private UserRepository repository;
...
}

This is why my preferred way of wiring components together is by configuration classes.

@Configuration
public ServiceConfiguration {
  @Autowired
  private UserRepository repository;
  @Bean
  public UserService userService() {
    return new UserVervice(repository);
  }
...
}

By doing so the @Service tag becomes unnecessary, plus I can keep all Spring specific annotations in one place: in the configuration classes. This is how I keep my repositories and services as clean POJOs.

The other topic I was missing from the 2nd chapter was how XML and annotation based configurations can work hand in hand.

Mixing XML and Java based configuration

When working on a “legacy” project which is still using XML based context configuration you can find yourself in a situation where you need to add some new configuration. And because it’s not 2009 you would like to use annotations. What can you do? Rewriting the whole configuration might require a significant amount of time and can be error-prone. Even if you aspire to do so in the long term, the best you can do is to start with incremental improvements. The Spring Framework provides a way to import Java configuration files into the XML context configuration.

First, you write your Java configuration like this:

@Configuration
class NewConfig {
  @Bean
  public DataRepostory dataRepository() {
  ....
  }
}

… and then import it into your XML config:

<bean class="org.randomdeveloper.spring5.config.NewConfig" />

By doing so you will have the ability to reference your new beans in the XML configuration – if required.

I hope you find my tips useful. Despite these shortcomings, I still think that Mastering Spring 5.0 is a very well written book. I suspect chapters about Spring Cloud will contain a lot of stuff that is new for me 😉

Leave a Reply

Your email address will not be published. Required fields are marked *