首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Spring中读取外部属性文件?

如何在Spring中读取外部属性文件?
EN

Stack Overflow用户
提问于 2019-03-09 03:03:41
回答 5查看 9K关注 0票数 0

每个人都知道,如果我们想要读取属性文件,我们可以这样做:

代码语言:javascript
复制
@Configuration
@PropertySource("classpath:/application.properties")
public class AppConfig {

    @Value("${app.name}")
    public String name;


    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public PostService postService() {
        return new PostServiceImpl(name);
    }

}

但是,现在我有了一个类似于SpringBoot的框架。它可以把Spring和Mybatis结合起来。

问题是前面的代码只能读取我的项目类路径文件,但是我需要使用我的框架读取属性文件项目。我是怎么做到的?

更新

我为大家感到遗憾。也许我说得不清楚,所以这是一幅画:

  • 我不使用SpringBoot
  • 我想阅读这个项目(使用我的框架)类路径,而不是我的框架类路径。

谢谢。

EN

回答 5

Stack Overflow用户

发布于 2019-03-09 08:09:42

Spring提供外部配置。这样,您就可以在不同的环境中运行应用程序。

参考链接:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

如果不喜欢application.properties作为配置文件名,则可以通过指定spring.config.name环境属性切换到另一个文件名。

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:db.properties")
@PropertySource("classpath:project.properties")
public class DBConfiguration {

@Autowired
Environment env;

  @Bean
  public DBConnection getDBConnection() {
    System.out.println("Getting DBConnection Bean for 
    App:"+env.getProperty("APP_NAME"));
    DBConnection dbConnection = new DBConnection(env.getProperty("DB_DRIVER_CLASS"), 
     env.getProperty("DB_URL"), env.getProperty("DB_USERNAME"), 
     env.getProperty("DB_PASSWORD").toCharArray());
    return dbConnection;
  }

 }

DB.properties:
#Database configuration
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:3306/Test
DB_USERNAME=root
DB_PASSWORD=root

project.properties:
APP_NAME=TEST APP
票数 1
EN

Stack Overflow用户

发布于 2019-03-09 06:54:58

Spring框架可以从不同的位置读取外部配置文件。它可以从您的项目目录中读取配置文件,但是您需要删除这一行:

代码语言:javascript
复制
@PropertySource("classpath:/application.properties")

这将它限制在应用程序类路径上。您可以检查这里以查看不同位置的spring读取配置文件。

票数 0
EN

Stack Overflow用户

发布于 2019-03-09 15:08:10

如果您只是希望自己从类路径中读取属性,则可以使用

代码语言:javascript
复制
Properties prop = new Properties();
InputStream input = this.getClass().getResourceAsStream("/application.properties")
prop.load(input);

// get the property value and print it out
System.out.println(prop.getProperty("foo"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55073597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档