springboot @PropertySource的使用案例
时间: 2024-05-08 16:17:54 浏览: 20
假设我们有一个Spring Boot应用程序,需要从外部配置文件加载某些属性。我们可以使用@PropertySource注释将外部属性文件加载到Spring Boot应用程序中。
例如,假设我们有一个名为application.properties的属性文件,其中包含以下属性:
```
server.port=8080
database.url=jdbc:mysql://localhost:3306/mydb
database.username=root
database.password=password
```
我们可以在Spring Boot应用程序中使用@PropertySource注释来加载这些属性文件,如下所示:
```java
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${server.port}")
private int serverPort;
@Value("${database.url}")
private String databaseUrl;
@Value("${database.username}")
private String databaseUsername;
@Value("${database.password}")
private String databasePassword;
// getters and setters
}
```
在这个示例中,我们使用@Configuration注释将类标记为配置类,并使用@PropertySource注释将属性文件加载到Spring Boot应用程序中。我们还使用@Value注释将属性值注入到应用程序中的变量中。
现在,我们可以使用这些属性来配置我们的应用程序,如下所示:
```java
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Autowired
private AppConfig appConfig;
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.setPort(appConfig.getServerPort());
return tomcat;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(appConfig.getDatabaseUrl());
dataSource.setUsername(appConfig.getDatabaseUsername());
dataSource.setPassword(appConfig.getDatabasePassword());
return dataSource;
}
}
```
在这个示例中,我们使用@Autowired注释将AppConfig类注入到MyApp类中,然后使用属性值来配置Tomcat服务器和数据源。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)