创建前缀一样的文件_SpringBoot:配置文件属性读取
时间: 2024-03-07 22:47:38 浏览: 19
您好!针对您的问题,创建前缀一样的文件可以使用Spring框架自带的`@ConfigurationProperties`注解,将同一前缀的属性封装到同一个对象中。具体实现步骤如下:
1. 在`application.properties`配置文件中添加属性:
```
myapp.datasource.url=jdbc:mysql://localhost:3306/mydb
myapp.datasource.username=root
myapp.datasource.password=123456
```
2. 创建一个`MyAppProperties`类,使用`@ConfigurationProperties`注解标记,并指定前缀:
```
@Configuration
@ConfigurationProperties(prefix = "myapp.datasource")
public class MyAppProperties {
private String url;
private String username;
private String password;
// 省略getter和setter方法
}
```
3. 在Spring Boot的主类中添加`@EnableConfigurationProperties`注解,并将`MyAppProperties`类作为参数传入:
```
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
```
4. 在需要使用属性的地方注入`MyAppProperties`对象即可:
```
@Service
public class MyService {
private final MyAppProperties properties;
public MyService(MyAppProperties properties) {
this.properties = properties;
}
public void doSomething() {
String url = properties.getUrl();
String username = properties.getUsername();
String password = properties.getPassword();
// 使用属性进行业务逻辑处理
}
}
```
这样就可以方便地管理同一前缀的属性了。希望对您有所帮助!