溫馨提示×

springboot怎么加載配置文件

小億
112
2023-11-28 11:53:06
欄目: 編程語言

Spring Boot通過@PropertySource注解來加載配置文件。

  1. @SpringBootApplication注解所在的類上添加@PropertySource注解,指定要加載的配置文件路徑。例如,加載名為application.properties的配置文件,代碼如下:
@SpringBootApplication
@PropertySource("classpath:application.properties")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  1. application.properties配置文件中,添加需要的配置項。例如:
server.port=8080
  1. 在需要獲取配置項的地方,使用@Value注解來注入配置項的值。例如,在一個@Component標注的類中獲取server.port配置項的值:
@Component
public class MyComponent {
    @Value("${server.port}")
    private String port;
    
    // ...
}

以上就是使用Spring Boot加載配置文件的方法。在配置文件中添加需要的配置項,并在需要使用的地方通過注解來獲取配置項的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女