Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 to DatabaseConfig.

There's more…

If you are using a Spring application without a ServletInitializer class, you can include other configuration classes from your primary configuration class:

@Configuration
@Import({ DatabaseConfig.class...