springboot如何在工具类中获取yml配置文件内容?

springboot框架,我想在一个工具类中获取yml配置文件的内容,获取不到,请教下大家该怎么做?谢谢!

浏览器请求地址:http://localhost:8080/getConfig


报错结果:


目录结构



Hello.java

package com.example.mytesttoolsymlwrong.web;

import com.example.mytesttoolsymlwrong.WebConfig;

import com.example.mytesttoolsymlwrong.tools.ToolsA;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication

@RestController

public class Hello {

@Autowired

private WebConfig webConfig;

@GetMapping("/getConfig")

public void getConfig() {

ToolsA toolsA=new ToolsA();

System.out.println(toolsA.getCommonKey());

}

}


ToolsA.java

package com.example.mytesttoolsymlwrong.tools;

import com.example.mytesttoolsymlwrong.WebConfig;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class ToolsA {

@Autowired

private WebConfig webConfig;

public String getCommonKey() {

System.out.println("======getCommonKey=========");

return webConfig.getMykey();

}

}


WebConfig.java

package com.example.mytesttoolsymlwrong;

import lombok.Data;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;

import org.springframework.stereotype.Component;

@Component

public class WebConfig {

@Value("${project.mykey}")

private String mykey;

public String getMykey() {

return mykey;

}

public void setMykey(String mykey) {

this.mykey = mykey;

}

}

application.yml

# 应用名称

spring:

application:

name: mytest-tools-yml-wrong

# 应用服务 WEB 访问端口

server:

port: 8080

project:

mykey: aaaaaa


回答:

你自己实例化的对象, 不归spring管, 里面的属性自己处理, 你没设置, 那就是没有值.

请使用 @Autowired ToolsA tools 让spring注入.


回答:

@GetMapping("/getConfig")

public void getConfig() {

ToolsA toolsA=new ToolsA();

System.out.println(toolsA.getCommonKey());

}

ToolsA toolsA=new ToolsA();
这个toolsA对象是你自己new出来的 不是spring容器里面的 所以为NULL了

以上是 springboot如何在工具类中获取yml配置文件内容? 的全部内容, 来源链接: utcz.com/p/944906.html

回到顶部