首页 > 解决方案 > 从 yml 配置获取值到依赖项

问题描述

我上课了:

@WebServiceClient(name = "${service.name}", targetNamespace = "${service.namespace}", wsdlLocation = "${service.wsdlLocation}")
public class ExampleService extends Service {
    @Value("${service.wsdlLocation}")
    private static String wsdlLocation;
}

它是 mvn 项目的一部分,我从本地 maven 存储库编译并使用它作为对我的其他 spring-boot 应用程序的依赖项,该应用程序具有配置 yml:

service:
  name: name
  namespace: namespace
  wsdlLocation: wsdlLocation

有没有办法让这个 ExampleService 类使用“父”项目的配置?

编辑:

出现了两个答案,但我觉得我没有问清楚。我现在要做的是在我的“父”项目中使用类 ExampleService 并让它看到该父项目的配置。到目前为止,例如,当我编写父项目代码时,例如:

ExampleService exampleService = new ExampleService();
System.out.println(exampleService.getWsdlLocation());

打印空值。所以我正在寻找一些解决方案。

编辑 2:这是我的课程。父项目:

package com.example.kris.parentservice;

import com.example.kris.childservice.ExampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/example")
public class ExampleController {

//    @Autowired
    private ExampleService exampleService;
    @Value(value = "${service.wsdlLocation}")
    private String wsdlLocation;

    @GetMapping(value = "/example")
    public void example() {
        exampleService = new ExampleService();
        System.out.println("ExampleService field: " + exampleService.getWsdlLocation());
        System.out.println("@Value: " + wsdlLocation);
    }
}

子项目:

package com.example.kris.childservice;

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

public class ExampleService {
    @Value("${service.wsdlLocation}")
    private String wsdlLocation;

    public String getWsdlLocation() {
        return wsdlLocation;
    }
}

并在运行父控制器后输出:

ExampleService field: null
@Value:test.wsdl.location

标签: javaspringspring-bootconfigurationyaml

解决方案


YamlPropertySourceLoader 可以在 spring boot 应用程序中注入这样的 bean

@Bean
public PropertySource<?> yamlPropertySourceLoader() throws IOException {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    PropertySource<?> applicationYamlPropertySource = loader.load("application.yml",
            new ClassPathResource("application.yml"), "default");
    return applicationYamlPropertySource;
}

推荐阅读