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

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

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


报错结果:

image.png


目录结构
image.png



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

阅读 2.3k
2 个回答

你自己实例化的对象, 不归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了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题