【发布时间】:2017-03-10 10:08:16
【问题描述】:
我在属性文件中编写了查询。我想在spring boot中将属性文件读入一个带有注释的类。我该如何阅读?在 Spring Boot 项目中编写查询有没有更好的方法?
【问题讨论】:
标签: spring spring-boot
我在属性文件中编写了查询。我想在spring boot中将属性文件读入一个带有注释的类。我该如何阅读?在 Spring Boot 项目中编写查询有没有更好的方法?
【问题讨论】:
标签: spring spring-boot
如果您在 application.properties 文件中添加属性,您可以在 Spring Boot 类中读取它们,例如:
@Service
public class TwitterService {
private final String consumerKey;
private final String consumerKeySecret;
@Autowired
public TwitterService(@Value("${spring.social.twitter.appId}") String consumerKey, @Value("${spring.social.twitter.appSecret}") String consumerKeySecret) {
this.consumerKey = consumerKey;
this.consumerKeySecret = consumerKeySecret;
} ...
【讨论】:
您可以通过@Value("${property.name}")注释组件中的字段
否则,您可以使用java.util 包中的Properties 对象。
例如,我有一个 mode 属性,其值为 dev 或 prod,我可以在我的 bean 中使用它,如下所示:
@Value("${mode:dev}")
private String mode;
另一种方法是使用:
Properties pro = new Properties();
pro.load(this.getClass().getClassLoader().getResourceAsStream());
【讨论】:
您可以使用@PropertySource 从文件中读取属性,然后将它们传递给bean。如果您有一个名为“queries.properties”的文件,其属性如下:
query1: select 1 from foo
那么您的配置可能如下所示:
@PropertySource("classpath:queries.properties")
@Configuration
public class MyConfig {
@Bean
public DbBean dbBean(@Value("${queries.query1}") String query) {
return new DbBean(query);
}
}
【讨论】: