springboot 引用部分外部配置文件方法
时间: 2023-08-08 09:00:58 浏览: 57
在Spring Boot中,可以使用@PropertySource注解来引用外部配置文件。
首先,在你的Spring Boot应用的主配置文件(通常是application.properties或application.yml)中添加以下配置:
```
spring.config.name=application
spring.config.location=classpath:/config/
```
这个配置告诉Spring Boot去查找名为application的配置文件,并将其位置设定为classpath:/config/,也就是在项目的src/main/resources目录下的config文件夹中。
接下来,在你的Spring Boot应用的启动类中,使用@PropertySource注解来引用外部配置文件。例如,如果你想引用一个名为custom.properties的配置文件,可以在启动类上添加@PropertySource注解:
```
@SpringBootApplication
@PropertySource("classpath:/config/custom.properties")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
```
然后,你就可以在应用中使用@Value注解来注入配置文件中的属性值了。例如,如果你的custom.properties文件中有一个属性名为custom.message,你可以在你的Spring Bean中使用@Value注解来注入这个值:
```
@Component
public class YourBean {
@Value("${custom.message}")
private String message;
// ...
}
```
这样,Spring Boot就会将配置文件中的custom.message属性值注入到YourBean的message属性中。
总结起来,只需要在主配置文件中配置外部配置文件的位置,然后使用@PropertySource注解来引用外部配置文件,最后使用@Value注解来注入配置文件中的属性值即可。