我目前正在学习如何使用 Spring Boot。到目前为止我从未使用过像Spring这样的框架,而是直接使用文件(FileInputStream等)
情况如下:我有一些动态配置值,例如 OAuth 令牌。我想在我的应用程序中使用它们,但我不知道如何用 Spring 实现这一点。
这是一些代码来明确我正在搜索的内容:
@Config("app.yaml")
public class Test {
@Value("app.token")
private String token;
private IClient client;
public Test(String token) {
this.client = ClientFactory.build(token).login();
}
}
当然,这个例子很简单。在这里,我想从 YAML 配置文件动态获取值“token”。该文件必须可供用户访问,并且不包含在 JAR 文件中。
我还发现了该文档:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html但我现在知道如何将其应用到我的项目中。
我怎样才能实现这个目标?先感谢您 :)
Edit:
这是我的代码的一些部分:
WatchdogBootstrap.java
package de.onkelmorph.watchdog;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("classpath:Beans.xml")
public class WatchdogBootstrap {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(WatchdogBeans.class);
app.setBannerMode(Mode.OFF);
app.setWebEnvironment(false);
app.run(args);
}
}
Beans.xml(位于默认包中)
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config></context:annotation-config>
</beans>
看门狗.java
package de.onkelmorph.watchdog;
// Imports ...
@Component
@PropertySource("file:/watchdog.yml")
public class Watchdog {
// ...
// Configuration
@Value("${watchdog.token}")
private String token;
public Watchdog() {
System.out.println(this.token);
System.exit(0);
}
// ...
}
看门狗.yml(位于 src/main/resources 中)
watchdog:
token: fghaepoghaporghaerg