在此处输入代码是否有一种方法可以仅在将配置文件读取为地图时获取特定于配置文件的属性
示例:
application-local.yml
user:
key1: value1
key2: value2
application-dev.yml
user:
key1: dev-value
key3: value3
当激活多个配置文件(例如“local,dev”)时,我喜欢仅将“用户”映射视为
{key1: dev-value, key3: value3}
。但目前它正在给予{key1: dev-value, key2:value2, key3:value3}
。
有办法实现吗?
创建一个@ConfigurationProperties类并使用@Profile注释指定配置文件
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@Profile("dev")
@ConfigurationProperties(prefix = "user")
public class DevUserProperties {
private Map<String, String> user;
public Map<String, String> getUser() {
return user;
}
public void setUser(Map<String, String> user) {
this.user = user;
}
}
创建另一个
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@Profile("local")
@ConfigurationProperties(prefix = "user")
public class LocalUserProperties {
private Map<String, String> user;
public Map<String, String> getUser() {
return user;
}
public void setUser(Map<String, String> user) {
this.user = user;
}
}
在您的服务中,根据活动配置文件注入 @ConfigurationProperties 类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class UserService {
private final DevUserProperties devUserProperties;
private final LocalUserProperties localUserProperties;
@Autowired
public UserService(DevUserProperties devUserProperties, LocalUserProperties localUserProperties) {
this.devUserProperties = devUserProperties;
this.localUserProperties = localUserProperties;
}
public Map<String, String> getUserProperties() {
if (devUserProperties != null && devUserProperties.getUser() != null) {
return devUserProperties.getUser();
} else if (localUserProperties != null && localUserProperties.getUser() != null) {
return localUserProperties.getUser();
}
return null;
}
}
通过这种方式,您可以激活多个配置文件并仅从特定配置文件获取属性。