我使用@PropertySource注释引用Spring中的属性源,但只有属性文件的名称为application.properties时,spring才能找到它。Spring无法加载属性文件
我的属性文件位于src/main/resources中。
我使用@PropertySource注释引用Spring中的属性源,但只有属性文件的名称为application.properties时,spring才能找到它。Spring无法加载属性文件
我的属性文件位于src/main/resources中。
您可能希望将您的配置设置为能够处理多个属性源。有很多方法可以做到这一点,但我建议您将您的属性配置与其他配置分开,以便模块化责任。虽然您也可以使用@Value注释来加载属性,但您可能需要考虑暂时自动装配环境。
@Configuration
@PropertySources({ // this takes in an array of property sources
@PropertySource("classpath:file.properties") // precede your property with classpath to find it in resources
})
public class MyConfiguration()
{
@Autowired
private Environment env;
@Bean
public String provideSomeString()
{
return env.getProperty("some.property.in.file"); // get the property from the property file
}
}
下面是使用@Value注释加载属性的快速方法。
@Configuration
@PropertySources({
@PropertySource("classpath:file.properties")
})
@Component
public class MyConfiguration()
{
@Value("${some.property.in.file}") // get the property from the property file
private String property;
@Bean
public String provideSomeString()
{
return property;
}
@Bean // this bean is required in order to pass properties into the @Value annotation, otherwise you will just get the literal string
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
{
return new PropertySourcesPlaceholderConfigurer();
}
}
我实际上使用Value注释来获取属性值,但只有当PropertySource是application.properties时才会加载值 –
什么值分配给字符串?你在用什么IDE?资源中的哪个部分是您尝试从中加载的资产?你能否更新你的问题来显示你的@PropertySource注解?我认为那是你的问题所在。 – tramstheman