springboot使用properties的复杂类型list/map(看这一篇就够了)
在Spring Boot中,你可以使用@ConfigurationProperties
注解将properties文件中的复杂类型映射到Java对象中。以下是如何定义和使用复杂类型List和Map的例子:
首先,在application.properties
或application.yml
中定义你的复杂类型:
custom:
users:
- name: user1
age: 30
- name: user2
age: 25
mappings:
key1: value1
key2: value2
然后,创建一个配置类来映射这些属性:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Map;
@Configuration
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
private List<User> users;
private Map<String, String> mappings;
// standard getters and setters
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Map<String, String> getMappings() {
return mappings;
}
public void setMappings(Map<String, String> mappings) {
this.mappings = mappings;
}
public static class User {
private String name;
private int age;
// standard getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
最后,在需要的地方注入CustomProperties
并使用它:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class MyService {
@Autowired
private CustomProperties customProperties;
public void printCustomProperties() {
List<CustomProperties.User> users = customProperties.getUsers();
for (CustomProperties.User user : users) {
System.out.println("Name: " + user.getName() + ", Age: " + user.getAge());
}
Map<String, String> mappings = customProperties.getMappings();
for (Map.Entry<String, String> entry : mappings.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
这样,你就可以在Spring Boot应用中使用复杂类型的List和Map了。
评论已关闭