4

Is it possible to configure spring to instantiate a bean or not, depending on a boolean placeholder property? Or at least to exclude a package from annotation scanning based on such a property?

Cœur
  • 37,241
  • 25
  • 195
  • 267
kgautron
  • 7,915
  • 9
  • 39
  • 60

5 Answers5

9

I think you should be using Spring profiles to configure different behaviours. However if you are using annotations you could create an @Configuration object and and a factory method to create a bean based on the property value

e.g.

@Configuration
class ExampleConfig {
    private final String prop;

    public ExampleConfig(@Value("${your.prop.name}" prop} {
       this.prop = prop;
    }

    @Bean 
    public YourBeanClass create() {
         if (prop.equals("someValue") {
            return new YourBeanClass();
         }
         return new OtherClass(); // must be subclass/implementation of YBC
    } 
}
Ayub Malik
  • 2,488
  • 6
  • 27
  • 42
8

You can use ConditionalOnProperty:

@Bean
@ConditionalOnProperty(value = "property", havingValue = "value", matchIfMissing = true)
public MyBean myBean() ...

Also, check this answer.

gce
  • 1,563
  • 15
  • 17
1

This may not fit your needs, and I'm assuming that you have control over the class in question (i.e. not vendor code), but have you considered marking the the bean to be lazy loaded? At least, that way it won't get instantiated until it actually gets used, which may happen conditionally depending on the rest of your configuration.

Ophidian
  • 9,775
  • 2
  • 29
  • 27
1

You can also use @Conditional

Step 1 : Create a class that implements Condition

public class ProdDataSourceCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    String dbname = context.getEnvironment().getProperty("database.name");
    return dbname.equalsIgnoreCase("prod");
}}

Step 2 : Use the above class with @Conditional

    @Configuration
    public class EmployeeDataSourceConfig {


  ....

    @Bean(name="dataSource")
    @Conditional(ProdDataSourceCondition.class)
    public DataSource getProdDataSource() {
      return new ProductionDatabaseUtil();
    }
    }

http://javapapers.com/spring/spring-conditional-annotation/

Ruchi Saini
  • 301
  • 2
  • 5
0

We can use ConditionalOnProperty . Just define a property deployment.environemnt in application.properties file . And based on this property you can control the creation of objects.

@Bean(name = "prodDatasource")
@ConditionalOnProperty(prefix = "deployment" name = "environment"havingValue = "production")
 public DataSource getProdDataSource() {
      return new ProductionDatasource();
  }


@Bean(name = "devDatasource")
@ConditionalOnProperty(prefix = "deployment" name = "environment"havingValue = "dev")
 public DataSource getDevDataSource() {
      return new devDatasource();
  }
Hamdhan Azeez T
  • 429
  • 4
  • 9