【发布时间】:2017-10-18 02:02:38
【问题描述】:
我在示例 Spring Boot 应用程序中有以下代码
@Configuration
@PropertySource("classpath:second.properties")
public class PropertyConfig {
@Value("#{guru.username}")
String user;
@Value("#{guru.password}")
String password;
@Value("#{guru.url}")
String url;
@Bean
FakeDataSource getFakeDataSource() {
FakeDataSource fk = new FakeDataSource();
fk.setName(user);
fk.setPassword(password);
fk.setUrl(url);
return fk;
}
@Bean
PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer placeholderConfigurer= new PropertySourcesPlaceholderConfigurer();
//placeholderConfigurer.setLocation(new ClassPathResource("second.properties"));
return placeholderConfigurer;
}
}
而 FakeDataSource 是一个简单的 pojo,具有 name、passowrd、url 属性。
然后是我的主应用程序
@SpringBootApplication
public class SpringGuru101DependencyInjectionApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringGuru101DependencyInjectionApplication.class, args);
// Step 2: Make Class
FakeDataSource fakeDataSource = ctx.getBean(FakeDataSource.class);
System.out.println(fakeDataSource.getName());
}
}
但是 sout 语句正在打印 null, 我的 second.properties 文件存在于我的资源目录中,内容如下
guru.username=Saurabh
guru.password=ido
guru.url=http://example.com
【问题讨论】:
-
试试
@ImportResource("classpath:second.properties") -
请尝试将井口符号 (#) 替换为美元符号 ($),以便从配置文件中读取值。例如:
@Value("${guru.username}") -
如果我使用 @ImportSource(classpath)
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [second.properties] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.@ScaryWombat 应用程序无法编译 -
@LHCHIN 仍然为空
-
@Saurabh 我写了
@ImportResource不是@ImportSource
标签: java spring spring-boot