问题:类似配置中心 apollo  ,修改后, 无法自动刷新 , 或者确实配置比较复杂, 确实需要通过前缀获取配置信息 

@Component
@ConfigurationProperties(prefix="apollo.test")
public class SeaUtil {

    private Map<String,Integer> mapkey=new HashMap<String,Integer>();
    public void setMapkey(Map<String, Integer> mapkey) {
        this.mapkey = mapkey;
    }
}

 

 

通过前缀获取

    @Autowired
    private ConfigurableEnvironment environment;
    /**
     * 根据用户名从配置文件中获取对应的office信息
     * 配置文件格式:
     * office.user.HKG=Sea,Zero
     * office.user.LAX=Sea,Zero
     * @param username
     * @return
     */
      public String getOfficeFromConfig_bk(String username) {
        if (username == null) {
            log.warn("Username is null, cannot get office from Redis");
            return null;
        }
        // office.user.HKG=Sea,YY,XX
        // office.user.LAX=Sea,YY,XX
        //environment 通过前缀获取所有的配置, 然后检测 username (Sea ) 是否包含,如果包含,获取   office 返回 office (HKG)
          List<String> matchedOffices = environment.getPropertySources().stream()
                  .flatMap(ps -> {
                      // 遍历当前 PropertySource 中的所有键
                      if (ps.getSource() instanceof Map) {
                          return ((Map<?, ?>) ps.getSource()).entrySet().stream()
                                  .filter(e -> e.getKey() instanceof String)
                                  .map(Map.Entry::getKey)
                                  .map(String.class::cast)
                                  .filter(key -> key.startsWith(OFFICE_PREFIX));
                      }
                      return Stream.empty();
                  })
                  .distinct()
                  .filter(key -> {
                      String users = environment.getProperty(key);
                      return users != null && Arrays.asList(users.split(",")).contains(username.trim());
                  })
                  .collect(Collectors.toList());
        if (matchedOffices!=null && !matchedOffices.isEmpty()) {
            return  matchedOffices.get(0).replace(OFFICE_PREFIX, "");
        }
          log.warn("No office found for user: {}", username);
          return null;
      }

 

posted on 2025-07-16 10:40  lshan  阅读(17)  评论(0)    收藏  举报