以下是一个示例代码,展示了如何使用Bazel读取Spring Boot的application.properties配置。
首先,我们需要在BUILD文件中添加相应的依赖项。假设我们使用的是Java和Spring Boot,可以在BUILD文件中添加以下内容:
load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_import")
kt_jvm_import(
name = "spring_boot",
jars = [
"@maven//:org_springframework_boot_spring_boot_starter_web",
"@maven//:org_springframework_boot_spring_boot_configuration_processor",
"@maven//:org_jetbrains_kotlin_kotlin_stdlib_jdk8",
],
deps = [
"@maven//:org_springframework_boot_spring_boot_configuration_processor"
],
)
接下来,我们需要在BUILD文件中添加一个包含配置文件的目录。假设我们的配置文件位于src/main/resources目录下,可以在BUILD文件中添加以下内容:
filegroup(
name = "resources",
srcs = glob(["src/main/resources/**"]),
visibility = ["//visibility:public"],
)
然后,我们可以在Java代码中使用Spring的@Value
注解来读取配置文件中的属性。例如,假设我们有一个名为MyService
的类,它需要读取配置文件中的属性my.property
:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Value("${my.property}")
private String myProperty;
public void printProperty() {
System.out.println("my.property: " + myProperty);
}
}
最后,我们可以编写一个包含main
方法的类来启动Spring Boot应用程序:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
MyService myService = context.getBean(MyService.class);
myService.printProperty();
}
}
通过以上步骤,我们可以使用Bazel构建并运行Spring Boot应用程序,并正确读取配置文件中的属性。