在Spring Boot應用程序中,可以通過在application.properties文件中定義屬性來讀取properties。
在resources文件夾下創建一個名為application.properties的文件。
在application.properties文件中定義屬性,例如:
myapp.property1=value1
myapp.property2=value2
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${myapp.property1}")
private String property1;
@Value("${myapp.property2}")
private String property2;
public void printProperties() {
System.out.println("Property 1: " + property1);
System.out.println("Property 2: " + property2);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApp implements CommandLineRunner {
@Autowired
private MyComponent myComponent;
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Override
public void run(String... args) throws Exception {
myComponent.printProperties();
}
}
通過以上步驟,就可以在Spring Boot應用程序中讀取定義的properties屬性了。