Using multiple configuration classes

A Spring configuration class can get quite long with many bean definitions. At this point, it can be convenient to break it into multiple classes.

Getting ready

We will use the code from the Defining a bean explicitly with @Bean recipe.

How to do it…

Here's how to add a second configuration class:

  1. Create a new configuration class, for example, DatabaseConfig in the com.springcookbook.config package:
    @Configuration
    public class DatabaseConfig {
    …
  2. In the ServletInitializer class, add the DatabaseConfig class in the getServletConfigClasses() method:
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{AppConfig.class, DatabaseConfig.class};
    }
  3. Move the Datasource bean from the AppConfig class ...

Get Spring Cookbook 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.