Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.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
Java Spring引导配置&;组件_Java_Spring_Spring Boot_Configuration - Fatal编程技术网

Java Spring引导配置&;组件

Java Spring引导配置&;组件,java,spring,spring-boot,configuration,Java,Spring,Spring Boot,Configuration,我正试图使用一个组件来加载我的配置yml文件 然而,它抛出了一个空指针异常,System.out为应用程序显示“Null” 然而,当使用相同的模式编写@RestController时,一切都正常。为什么@component看不到我的配置 @Component @ConfigurationProperties(prefix = "myconf") public class AppConfigJSON { private String application; private fi

我正试图使用一个组件来加载我的配置yml文件

然而,它抛出了一个空指针异常,System.out为应用程序显示“Null”

然而,当使用相同的模式编写@RestController时,一切都正常。为什么@component看不到我的配置

@Component
@ConfigurationProperties(prefix = "myconf")
public class AppConfigJSON {

    private String application;
    private final String applicationConfigJSON;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ReadContext acRcJson;

public AppConfigJSON(){
        String json = "";
        try {
            System.out.println("Application: " + this.application);
            json = IOUtils.toString(this.getClass().getResourceAsStream("/myconfs/"+this.application+".json"));
        } catch (IOException e) {
            logger.error("Error reading JSON or app YML {}", e.getStackTrace());            
        }
        this.applicationConfigJSON = json;
        this.acRcJson = JsonPath.parse(this.getApplicationConfigJSON());
    }


// These functions below set by configuration
public String getApplication()
{
    return application;
}

public void setApplication(String application)
{
    this.application = application;
}

}

在您的构造函数中,应用程序变量尚未初始化,换句话说,Spring首先需要一个实例,以便应用它的魔力。您需要将构造函数逻辑移动到用
@postcontract
注释的方法,以便应用程序变量在该点设置属性值。

确保AppConfigJSON类包位于应用程序中定义的basePackageScan下。我如何做?它在同一个包裹里。与我的@springbootplication.P.s相同级别。它在同一级别的控制器中检测到它。。。但不是在我制作的组件类中。我在这节课上做了一个测试,即使这样也不起作用。两者都表示“application:null”,如果删除“parse”(因为我无法解析“null应用程序变量”),NullPointerException也会消失。但是为什么配置yml不会放在我的组件中呢?这正是我1分钟前发现的,哈哈,但我已经一个多小时没有检查它了。你是对的。@PostConstruct void init()抛出IOException{}