Search code examples
spring-bootconfigurationsetcookie

Spring boot: apply @Configuration to certain package only


I am using @Configuration to config cookies, while in my project there is 2 packages and I only want to apply the config to one of the package.
Are there any ways to set the target package for @Configuration?

package structure:
--app
----packageA
------MyConfigClass.java
----packageB

@EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 1800)
@Configuration
public class MyConfigClass extends WebMvcConfigurerAdapter {
@Bean
    public CookieSerializer cookieSerializer() {
        // I want the follow cookie config only apply to packageA
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("myCookieName");
        serializer.setCookiePath("/somePath/");
        return serializer;
    }
}

Solution

  • Actually, you can use @ComponentScan to specify which packages to scan for and @EnableAutoConfiguration with the exclude options to omit the classes that you want to omit. You have to use this in your main application class.

    @EnableAutoConfiguration(exclude = { Class1.class,
            Class2.class,
            Class3.class }, 
    excludeName = {"mypackage.classname"}))
    @Configuration
    @ComponentScan(basePackages = { "mypackage" })
    public class MyApplication {
    
    public static void main(String[] args) throws Exception {
            SpringApplication.run(MyApplication.class, args);
        }
    }
    

    Alternatively, you can also provide the classes that you want to exclude in your configuration file.

    # AUTO-CONFIGURATION
    spring.autoconfigure.exclude= # Auto-configuration classes to exclude.