Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable creating bean with @Component annotation in Spring?

I have some common interface for refactoring logic in my project. It looks about like this:

public interface RefactorAwareEntryPoint {

    default boolean doRefactor() {
        if (EventLogService.wasEvent(getEventType())) {
            return true;
        }
        boolean result = doRefactorInternal();
        if (result) {
            EventLogService.registerEvent(eventType);
        }
        return result;
    }

    String getEventType();
    
    boolean doRefactorInternal();
}

And than, when I need to write some refactoring - I implement this interface with methods, mark class like @Component, and Spring in loop evaluate each interface implementation and register it in database. But we have a lot of refactors (every year - 200-300 new). It's hard to disable old implementations manualy, and we have a lot of beans in our spring-context. Can we do something, for example, use some annotation - which will disable component creation by some condition?

For example:

@Component
@Enabled(YEAR.2020)
public class CustomRefactor implements RefactorAwareEntryPoint {
 // Code implementation
}

And this annotation will work like this (a pseudocode):

if (YEAR.2020) {
  create bean -> new CustomRefactor()
}

And when it will be YEAR.2021 - we will have no beans from YEAR.2020 in spring-context.

like image 351
Anton Avatar asked Dec 30 '22 21:12

Anton


1 Answers

Use the annotation @Profile that makes application configuration and beans available in certain environments.

You can find more at Spring Boot 2.4.0 reference documentation: 3. Profiles

Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. Any @Component, @Configuration or @ConfigurationProperties can be marked with @Profile to limit when it is loaded

Consider each year as a separate environment.

@Component
@Profile("2020")
public class CustomRefactor2020 implements RefactorAwareEntryPoint {
 // Code implementation
}
@Component
@Profile("2021")
public class CustomRefactor2021 implements RefactorAwareEntryPoint {
 // Code implementation
}
like image 148
Nikolas Charalambidis Avatar answered Jan 02 '23 11:01

Nikolas Charalambidis