Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Condition not able to read value from property file

I am trying to implement Spring Condition org.springframework.context.annotation.Conditionas follows:

public class APIScanningDecisionMaker implements Condition {

   @Override
   public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

    // Not able to read the property "swagger.scanner.can.run". It is always NULL.
    String canRunFlagInStr = context.getEnvironment().getProperty("swagger.scanner.can.run");
   // Ignore the rest of the code.
   }
}

However, as shown in the above code, when I read the property "swagger.scanner.can.run" it is always NULL. In my property file I have set it to "swagger.scanner.can.run=false".

I also tried to use the @Value("${swagger.scanner.can.run}") but even that returns NULL. When I put a debug in this method I can see that it is being called.

Just for the sake of completion I am using the APIScanningDecisionMaker as follows:

@Configuration
@EnableSwagger
@Conditional(APIScanningDecisionMaker.class)
public class CustomSwaggerConfig {
  // Ignore the rest of the code
}

Is there any reason why "swagger.scanner.can.run" is being retrieved as NULL?

like image 677
Raj Avatar asked Sep 25 '15 20:09

Raj


People also ask

How to set property values in spring reading properties file?

In Spring reading properties file and setting property values can be done using- Suppose you have your Database properties in a properties file called db.properties residing under config folder under resources folder.

What happens if property source is not found in spring?

If one or more specified PropertySource file is not found, spring will throw an Exception. 5. Ignore a Property file if not found Occasionally, you may want the app to ignore the property source not found exception. Spring throws an exception when a specified file is not found.

What is the use of property file in spring?

The property file is used to contain the property values of the Spring application. We can use it to hold the field values of a bean. It uses .properties extension to create a file as a property file. To load the property file, Spring provides @PropertySource annotation and <context:property-placeholder> tag.

What is the difference between @value and @propertysource annotation in spring?

Rather than using @Value annotation, Environment should be used to read properties file in Spring. Actually @PropertySource annotation adds a PropertySource to Spring's Environment so that can be used to make your code simpler.


1 Answers

Maybe spring doesn't know the file ?

This can be fix on annotated your class where the @Value("${swagger.scanner.can.run}")is used :

@PropertySource(value="classpath:config.properties")

Regards,

like image 160
fabien t Avatar answered Oct 05 '22 23:10

fabien t