如何为 spring 引导创建内部属性文件?

How do I create a internal properties file for spring boot?

我目前有一个外部属性文件,它正在被输入流调用。但是当我将我的 jar 文件上传到 cloud foundry 时,我的应用程序不会 运行.

代码片段

    public static void main(String[] args) {
    SpringApplication.run(App.class, args);


    Properties prop = new Properties();

    InputStream input = null;
    try {
        Date sysDate = new Date();
        String dateString = sysDate.toString();
        logger.info(" Application Started Time : " + dateString);

        input = new
        FileInputStream("C:/Users/Jackie/workspace/springApplication/myConfig.properties");
        prop.load(input);

在我的属性文件中,我有很多文本,它们用在我的 java 应用程序中。在我进行研究时,我似乎需要将我的属性文件更改为 spring 引导格式?对吗?

属性片段

mailhost=mailman@mail.com
mailToException=TheReal_mailman@mail.com
mailwhengreen = TheReal_mailman@mail.com
mailTo = TheReal_mailman@mail.com
mailFrom = messenger21@yahoo.com
mailFromwhengreen = messenger21@yahoo.com
subject= You got mail!

这是来自 cloud foundry 的日志。

errors from cf

当您的属性文件是静态的、在应用程序启动时加载一次并且在应用程序生命周期中不会更改时,下面的答案就可以了。 如果您需要在应用程序运行时解析属性文件,那么 Spring 配置文件不是正确的位置,您确实需要自己处理属性(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html#resources-implementations-filesystemresource 应该可以帮助您)

无需自己阅读和解析属性文件。

您认为最简单的方法就是使用配置文件。 您启用名为 someProfile 的配置文件,然后 spring 将查找名为 application-someProfile.properties.

的属性文件

如果找到外部(在您打包的 jar 之外)文件,将被使用。否则将使用内部(打包在您的 jar 中)文件。澄清于 http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config

Properties are considered in the following order:

(...)

  1. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants) Profile-specific
  2. application properties packaged inside your jar (application-{profile}.properties and YAML variants)

拥有没有匹配属性文件的配置文件是完全没问题的。

通过在任何 @Configuration class.

上添加 @Profile("production") 激活配置文件

还可以使用 spring.profiles.active 环境变量列出活动配置文件(您可以在启动应用程序时设置此变量)。

要读取属性值,您可以执行以下操作之一

  • @Autowire org.springframework.core.env.Environment 实例到您的 class 并调用 getProperty
  • 注入带有@Value("${propertyName}") 注释的字符串变量

勾选http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html 有关 Spring 引导属性的更多详细信息。

检查 http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html 以获取有关配置文件的更多信息。

如果您的属性文件出现错误,您应该会在应用程序启动时(在上下文加载期间)收到错误消息。要检查加载的属性,您可以使用 http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

env 端点将是最有用的,因为它会列出

  • 所有启用的配置文件
  • 所有加载的属性文件
  • 所有加载的属性