【问题标题】:Spring cannot read from property fileSpring 无法从属性文件中读取
【发布时间】:2018-10-08 19:24:02
【问题描述】:

有一个用@Service注解的类,尝试使用值读取属性,值总是为零

@Service
public class custom implements Conditional
{
@Value("${test.property}")
private boolean properttyValue;

}


#test.properties 
test.property= true

如果我在@Value 中提供任何不存在的值,它会抛出一个错误,这意味着属性已加载,

知道有什么问题吗?

【问题讨论】:

  • 确保您的课程被您的主要课程@ComponentScan 接听。是吗?
  • 是的,同一个包中的另一个类工作正常..

标签: spring properties


【解决方案1】:

这是因为 test.propeties 不在类路径中。如果您使用 Spring boot,请使用 -Dspring.config.location 指定外部配置。您可以通过以下方式做到这一点

-Dspring.config.location=your/config/dir/
-Dspring.config.location=classpath:pro1.properties,classpath:prop2.properties

如果你没有使用 Spring boot,这可以使用

@Configuration
@PropertySource("classpath:test.properties")
public class PropertiesWithJavaConfig {
    //...
}

@Configuration
@PropertySource({ 
  "classpath:test.properties"
})
public class PropertiesWithJavaConfig {
    //...
}

对于外部文件,可以使用“file:/”代替类路径,例如file:./,file:./config/

【讨论】:

  • 我不认为这是原因,因为我在同一个包中有一个类似的文件,弹簧可以加载,唯一的区别是,这实现了条件 - 编辑了问题
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多