我有以下课程:
public class ServiceFactory {
private ServiceFactory() {
}
public static <T extends XXXX> T loadService(Class<T> klass) {
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
return applicationContext.getBean(klass);
}
}它在运行时加载bean(我有一个特殊的理由这样做)。
我需要检查这个bean是否被@Scope(BeanDefinition.SCOPE_PROTOTYPE)注释,或者只是强制它成为一个原型。
我该怎么做?
发布于 2019-02-28 15:10:25
首先,您需要为您的类找到一个bean名。然后,您可以使用该名称查找BeanDefinition并获取范围。
public <T> String findScope(ConfigurableApplicationContext applicationContext, Class<T> type) {
String[] names = applicationContext.getBeanFactory().getBeanNamesForType(type);
if(names.length != 1){
throw new IllegalArgumentException("Could not find bean of type" + type.getCanonicalName());
}
return applicationContext.getBeanFactory().getBeanDefinition(names[0]).getScope();
}https://stackoverflow.com/questions/54928177
复制相似问题