首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring - @PropertySource,获取NPE ;(

Spring - @PropertySource,获取NPE ;(
EN

Stack Overflow用户
提问于 2015-05-17 09:25:09
回答 1查看 2.3K关注 0票数 1

我在使用@PropertySource时遇到了一些问题,我在使用env.getProperty(..)时得到了一个NPE。有人有洞察力吗?

我的环境:

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

堆叠痕迹:

代码语言:javascript
复制
Exception in thread "main" java.lang.NullPointerException
    at com.mycompany.app.ExpressiveConfig.main(ExpressiveConfig.java:33)

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

代码语言:javascript
复制
disc.title=Sgt.PeppersLonelyHeartsClubBand
disc.artist=TheBeatles

我的配置类:

代码语言:javascript
复制
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();
    }

}

模型类:

代码语言:javascript
复制
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注释,例如使用文件:前缀和属性文件的绝对路径。在类路径eg/@PropertySource("classpath:com/mycompany/app/app.properties").之前删除反斜杠将属性文件放在不同的位置。
  2. 我也尝试过使用包含@PropertySources注释的@PropertySource
  3. 我补充说: @Bean公共静态PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {返回新的PropertySourcesPlaceholderConfigurer();}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-17 09:37:44

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

您需要为该类型创建一个具有bean定义的应用程序上下文,并从其中检索实例。

要做到这一点,请将ExpressiveConfig注释为spring @Configuration,然后不实例化它,只需将该类传递给AnnotationConfigApplicationContext即可。然后,您将能够使用getBean(...)从上下文中检索bean。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30285382

复制
相关文章

相似问题

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