在Spring Boot中,可以使用@PropertySource注解来访问外部的配置文件。@PropertySource注解可以加载一个或多个外部的配置文件,并将其合并成一个Properties对象,然后将其注入到Environment中。

以下是一个示例:

  1. 创建一个外部的配置文件,例如application.properties,并将其放置在项目的根目录下或者classpath下。

  2. 在Spring Boot的入口类上添加@PropertySource注解,并指定外部配置文件的路径。例如:

@PropertySource("classpath:application.properties")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 在需要访问配置文件的地方,可以通过@Value注解来注入配置值。例如:
@Service
public class MyService {

    @Value("${my.property}")
    private String myProperty;

    // ...
}

在上面的示例中,${my.property}表示要访问application.propertiesmy.property的配置值。

注意:如果外部的配置文件与application.properties中的配置项有冲突,外部配置文件的优先级会更高

springboot 访问外部配置文件

原文地址: https://www.cveoy.top/t/topic/hIeX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录