Spring Condition无法从属性文件中读取值
我正在尝试实现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?
如果将@Conditional
添加到config类,则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
。
也许spring不知道文件?
这可以修复使用@Value("${swagger.scanner.can.run}")
类的注释:
@PropertySource(value="classpath:config.properties")
问候,
实现“Condition”的类的对象是通过Spring的构造函数创建的,因此您无法使用@Value注释注入值。 您可以在代码中执行以下操作:
@Override public boolean matches( ConditionContext arg0, AnnotatedTypeMetadata arg1) { String prop = conditionContext.getEnvironment() .getProperty("arg0"); //further code }
这对我来说很好
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; }