【问题标题】:Spring - @PropertySource, getting an NPE ;(Spring - @PropertySource,获得 NPE ;(
【发布时间】:2015-07-28 21:44:16
【问题描述】:

我在使用 @PropertySource 时遇到了一些问题,我在使用 env.getProperty(..) 时遇到了 NPE。 有人有什么见解吗?

我的环境:

  • JDK/JRE:1.6.0_06
  • 操作系统:Linux Mint 13
  • 春季:4.1.6.RELEASE

堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at com.mycompany.app.ExpressiveConfig.main(ExpressiveConfig.java:33)

属性文件/src/main/resources/com/mycompany/app/app.properties

disc.title=Sgt.PeppersLonelyHeartsClubBand
disc.artist=TheBeatles

我的配置类:

package com.mycompany.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;

@PropertySource("classpath:/com/mycompany/app/app.properties")
public class ExpressiveConfig {

    @Autowired
    Environment env;

    @Bean
    public App get() {
        return new App("hello", env.getProperty("disc.artist"));
    }

    public static void main(String args[]) {
        App a = new ExpressiveConfig().get();
    }

}

模型类:

package com.mycompany.app;

import org.springframework.stereotype.Component;

public class App {

      private final String title;
      private final String artist;

      public App(String title, String artist) {
        this.title = title;
        this.artist = artist;
      }

      public String getTitle() {
        return title;
      }

      public String getArtist() {
        return artist;
      }
}

尝试失败:

  1. 我尝试过使用@PropertySource 注释,例如使用文件:属性文件的前缀和绝对路径。 在类路径之前删除反斜杠,例如/@PropertySource("classpath:com/mycompany/app/app.properties")。 将属性文件放在不同的位置。

  2. 我也尝试过使用包含@PropertySource 注释的@PropertySources

  3. 我已添加:

    @豆 公共静态 PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 返回新的 PropertySourcesPlaceholderConfigurer(); }

非常感谢任何帮助/建议!

【问题讨论】:

  • 你是如何初始化 ExpressiveConfig 的?
  • 你测试过:@PropertySource("classpath:app.properties")?

标签: java spring


【解决方案1】:

Spring 只会将依赖项注入到它自己管理的 bean 中。由于您是自己创建该实例 (new ExpressiveConfig()),因此不会执行依赖注入,因为实际上根本不涉及 Spring。

您需要使用该类型的 bean 定义创建应用程序上下文并从那里检索实例。

为此,请将您的ExpressiveConfig 注释为弹簧@Configuration,然后,您无需自行实例化它,而是将该类传递给AnnotationConfigApplicationContext。然后,您将能够使用 getBean(...) 从上下文中检索您的 bean。

【讨论】:

  • 哇!感谢您非常及时的回答!像魅力一样工作!
  • 很高兴听到这个消息。如果它解决了您的问题,请接受答案。
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 2014-02-11
  • 1970-01-01
  • 2017-03-25
  • 2023-03-23
  • 2014-07-21
  • 2017-04-18
  • 1970-01-01
相关资源
最近更新 更多