gpt4 book ai didi

java - 从 yml 配置获取值到依赖项

转载 作者:行者123 更新时间:2023-12-01 23:23:23 25 4
gpt4 key购买 nike

我上课了:

@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());

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

编辑2:这是我的类(class)。父项目:

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;
}
}

运行父 Controller 后输出:

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

最佳答案

YamlPropertySourceLoader 在 Spring Boot 应用程序注入(inject)像这样的 bean 时很有帮助

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

关于java - 从 yml 配置获取值到依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com