Spring Condition not able to read value from property file

后端 未结 4 889
耶瑟儿~
耶瑟儿~ 2021-01-11 13:24

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

public class APIScanningDecisionMaker impl         


        
相关标签:
4条回答
  • 2021-01-11 13:50

    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,

    0 讨论(0)
  • 2021-01-11 13:55

    this works fine for me

    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        try {
            InputStream i = conditionContext.getResourceLoader().getResource("prop.file").getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(i));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            System.out.println(out.toString());
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return true;
    }
    
    0 讨论(0)
  • 2021-01-11 14:00

    The object of class implementing "Condition" is created via constructor from Spring, so you can not inject values using @Value annotation. You can do something like below in your code:

    @Override        
    public boolean matches(
    ConditionContext arg0, 
                AnnotatedTypeMetadata arg1) {       
            String prop = conditionContext.getEnvironment()
                     .getProperty("arg0");   
    //further code   
         }    
    
    0 讨论(0)
  • 2021-01-11 14:01

    If you add @Conditional to config class then APIScanningDecisionMaker should implement ConfigurationCondition. And don't forget to add @PropertySource to config class.

    import org.springframework.context.annotation.ConfigurationCondition;
    
    public class APIScanningDecisionMaker implement ConfigurationCondition {
        @Override
        public ConfigurationPhase getConfigurationPhase() {
            return ConfigurationPhase.REGISTER_BEAN;
        }
    }
    

    Properties will have been loaded in ConfigurationPhase.REGISTER_BEAN phase.

    If you use @Conditional for methods then you could implement Condition.

    0 讨论(0)
提交回复
热议问题