Boot - 查看加入已经加入 Refresh Scope的 所有 Bean
场景
有些时候,可能需要查看 可以刷新的 bean, 而 这些 Bean 都是放在 RefreshScope
类中,瞅瞅这个 bean 并没有想要暴露这些信息,怎么办呢?
好在 RefreshScope 内部是通过 ScopeCache 进行缓存,默认是 StandardScopeCache ,那么就简单了
RefreshScope 自动装配
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RefreshScope.class)
@ConditionalOnProperty(name = RefreshAutoConfiguration.REFRESH_SCOPE_ENABLED, matchIfMissing = true)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
@EnableConfigurationProperties(RefreshAutoConfiguration.RefreshProperties.class)
public class RefreshAutoConfiguration {
/**
* Name of the refresh scope name.
*/
public static final String REFRESH_SCOPE_NAME = "refresh";
/**
* Name of the prefix for refresh scope.
*/
public static final String REFRESH_SCOPE_PREFIX = "spring.cloud.refresh";
@Bean
@ConditionalOnMissingBean(RefreshScope.class)
public static RefreshScope refreshScope() {
return new RefreshScope();
}
}
自定义 ScopeCache
public class MyStandardScopeScope implements ScopeCache {
private final ConcurrentMap<String, Object> cache = new ConcurrentHashMap<String, Object>();
public Object remove(String name) {
return this.cache.remove(name);
}
public Collection<Object> clear() {
Collection<Object> values = new ArrayList<Object>(this.cache.values());
this.cache.clear();
return values;
}
public Object get(String name) {
return this.cache.get(name);
}
public Object put(String name, Object value) {
Object result = this.cache.putIfAbsent(name, value);
if (result != null) {
return result;
}
return value;
}
/**
* 显示所有 refresh scope 类型的 bean 名称
* @return
*/
public List<String> keys(){
return new ArrayList<>(this.cache.keySet());
}
public Collection<Object> values() {
Collection<Object> values = new ArrayList<Object>(this.cache.values());
return values;
}
}
替换原始的 RefreshScope 自动装配
@Configuration
public class ScopeConfig {
@Bean
public ScopeCache scopeCache(){
return new MyStandardScopeScope();
}
@Bean
public RefreshScope refreshScope(ScopeCache cache){
RefreshScope refreshScope = new RefreshScope();
refreshScope.setScopeCache(cache);
return refreshScope;
}
}
查看加入 RefreshScope 的Bean
@RestController
public class RefreshScopeController {
@Autowired
private RefreshScope refreshScope;
@Autowired
private BeanFactory factory;
@Autowired
private ScopeCache scopeCache;
@GetMapping("/scopes")
public List<String> scopes() {
String[] registeredScopeNames = ((ConfigurableBeanFactory) factory).getRegisteredScopeNames();
return Arrays.asList(registeredScopeNames);
}
@GetMapping("/scope/beans")
public List<String> scopeBeans() {
return ((MyStandardScopeScope) scopeCache).keys();
}
}
访问 http://localhost:8080/scope/beans
// 20220823083206
// http://localhost:5558/scope/beans
[
"scopedTarget.dpDsConfiguration",
"scopedTarget.druid"
]
good luck!