Spring Condition无法从属性文件中读取值

时间:2015-09-25 20:24:26

标签: java spring spring-mvc

我正在尝试按如下方式实现Spring Condition org.springframework.context.annotation.Condition

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.
   }
}

但是,如上面的代码所示,当我读取属性“swagger.scanner.can.run”时,它总是为NULL。在我的属性文件中,我将其设置为“swagger.scanner.can.run = false”。

我也尝试使用@Value("${swagger.scanner.can.run}"),但即使返回NULL也是如此。当我在这个方法中调试时,我可以看到它被调用。

为了完成,我使用APIScanningDecisionMaker如下:

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

有没有理由将“swagger.scanner.can.run”检索为NULL?

3 个答案:

答案 0 :(得分:1)

也许春天不知道文件?

这可以修复使用@Value("${swagger.scanner.can.run}")的类注释:

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

此致

答案 1 :(得分:0)

如果您将@Conditional添加到配置类,那么APIScanningDecisionMaker应该实现ConfigurationCondition。并且不要忘记将@PropertySource添加到配置类。

import org.springframework.context.annotation.ConfigurationCondition;

public class APIScanningDecisionMaker implement ConfigurationCondition {
    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }
}

属性将在ConfigurationPhase.REGISTER_BEAN阶段加载。

如果您使用@Conditional方法,则可以实施Condition

答案 2 :(得分:-2)

这对我来说很好

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;
}
相关问题