Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将属性文件加载到带有注释的spring启动项目中?_Spring_Spring Boot - Fatal编程技术网

如何将属性文件加载到带有注释的spring启动项目中?

如何将属性文件加载到带有注释的spring启动项目中?,spring,spring-boot,Spring,Spring Boot,我在属性文件中编写了查询。我想在spring boot中将属性文件读入一个带有注释的类中。我怎么读呢?在spring boot项目中编写查询有更好的方法吗?您可以通过@Value(${property.name}”) 否则,您可以在java.util包中使用Properties对象 例如,我有一个mode属性,它的值是dev或prod,我可以在我的bean中使用它,如下所示: @Value("${mode:dev}") private String mode; 另一种方法是使用: Proper

我在属性文件中编写了查询。我想在spring boot中将属性文件读入一个带有注释的类中。我怎么读呢?在spring boot项目中编写查询有更好的方法吗?

您可以通过
@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());

如果在application.properties文件中添加属性,则可以在spring引导类中读取它们,如:

    @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;
        } ...

您可以使用@PropertySource从文件中读取属性,然后将它们传递给bean。如果您有一个名为“querys.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);
 }
}