java - 从 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
解决方案
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;
}
推荐阅读
- javascript - jquery 掩码仅在加载 ajax 内容后工作一次
- variables - sql语句中的变量使查询挂起
- javascript - Supertest / Jest / Node - 无法测试简单的路线
- regex - 如何在我的 Angular 6 正则表达式中忽略大小写?
- node.js - 将多个集合传递到同一条快速路线
- julia - 如何在 Julia 中加速多个广播
- qt - 在 QtCreator 中的小部件之后添加布局
- javascript - 如果选中复选框 javascript,则在 30 秒后重定向
- php - PHP - Scrape data of all trustpilot reviews
- css - 仅当元素位于屏幕的某个位置时如何触发动画?