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

作者站长头像
站长
· 阅读数 12

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

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


报错结果:

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


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



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

回复
1个回答
avatar
test
2024-07-13

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

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

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容