Gagan
Gagan

Reputation: 145

How to exclude some @Configuration and only import them using @Import in Spring boot

I'm developing a spring-boot webapp which has the following package structure..

- com.myname.configs
    - CommonConfiguration.java  
    - DevConfiguration.java  
    - ProdConfiguration.java
    - SomeOtherConfiguration.java
- com.myname.profiles
    - DevProfile.java
    - ProdProfile.java

All of these classes are @Configuration classes but the DevProfile.java and ProdProfile.java also have the @Profile and @Import annotations.

CommonConfiguration..

@Configuration  
public class CommonConfiguration {  
    //commmon configs / beans..  
}  

DevConfiguration..

@Configuration
@Profile("dev")
public class DevConfiguration {

    @Bean
    //dev specific beans..
}

DevProfile..

@Configuration  
@Import(value = {CommonConfiguration.class, DevConfiguration.class})  
@Profile("dev")  
public class DevProfile {}  

ProdProfile..

@Configuration
@Import(value = {CommonConfiguration.class, ProdConfiguration.java})
@Profile("prod")
public class ProdProfile {}

For some reason, even with -Dspring.profile.active=prod, the beans for DevConfiguration are created. The only workaround is to add a @Profile("dev") annotation to DevConfiguration.java

Is there a way to only create the beans for classes in the @Import annotations? It seems logical to manage the Imports in one Profile class than add the Profile to various Configuration classes.

I'm looking for a way to do what @Aaron Digulla suggested in #1 here How to exclude some @Configuration file in Spring?

Upvotes: 2

Views: 18141

Answers (3)

Nikolai
Nikolai

Reputation: 785

If you use config-classes(CommonConfiguration,DevConfiguration and etc.) only by importing in profile-classes (DevProfile and etc.) then you just may remove @Configuration from config-classes.
In this case beans from config-classes will be created only via active profile-class (now config-classes and profile-classes are both scanned by spring for beans but @Profile("...") affect only to profile-classes).

Upvotes: 4

Gagan
Gagan

Reputation: 145

Actually, shortly after posting the comment I found the answer. It is Kirby's answer here Exclude subpackages from Spring autowiring?

In my case I've added this after the @SpringBootApplication annotation.

@SpringBootApplication
@ComponentScan(basePackages = { "com.myname" },
              excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "com.myname.configs.*"))
public class DemoWebappApplication {...}  

With this, the profile classes are being wired along with the @Imports in them.

Upvotes: 2

satya srinivas vemuri
satya srinivas vemuri

Reputation: 11

Did you try @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) annotation in below link (16.2 section)

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html

Upvotes: 0

Related Questions