下面列出了org.springframework.context.ApplicationContext#getBeanNamesForType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void setApplicationContext(ApplicationContext context) throws BeansException {
log.debug("setAC: " + context.getDisplayName());
String[] autobeans = context.getBeanNamesForType(AutoRegisterEntityProvider.class, false, false);
StringBuilder registeredPrefixes = new StringBuilder();
for (String autobean : autobeans) {
AutoRegisterEntityProvider register = (AutoRegisterEntityProvider) context
.getBean(autobean);
if (register.getEntityPrefix() == null || register.getEntityPrefix().equals("")) {
// should this die here or is this error log enough? -AZ
log.error("Could not autoregister EntityProvider because the enity prefix is null or empty string for class: "
+ register.getClass().getName());
} else {
registeredPrefixes.append(" : " + register.getEntityPrefix());
entityProviderManager.registerEntityProvider(register);
}
}
log.info("AutoRegistered EntityProvider prefixes " + registeredPrefixes);
// TODO - deal with de-registration in the case we ever support dynamic contexts.
}
public static void main(String[] args) {
// 1.读取xml
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Bean.xml");
//Person person = (Person) applicationContext.getBean("person");
//System.out.println(person);
// 2.读取配置类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (int i = 0; i < namesForType.length; i++) {
String s = namesForType[i];
System.out.println(s);
}
}
/**
* 建立当前 ApplicationContext 中的所有 Controller 和 url 的对应关系
*/
protected void detectHandlers() throws BeansException {
ApplicationContext applicationContext = obtainApplicationContext();
// 获取 ApplicationContext 容器中所有 bean 的 Name
String[] beanNames = (this.detectHandlersInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class) :
applicationContext.getBeanNamesForType(Object.class));
// 遍历 beanNames,并找到这些 bean 对应的 url
for (String beanName : beanNames) {
// 找 bean 上的所有 url(Controller 上的 url+方法上的 url),该方法由对应的子类实现
String[] urls = determineUrlsForHandler(beanName);
if (!ObjectUtils.isEmpty(urls)) {
// // 保存 urls 和 beanName 的对应关系,put it to Map<urls,beanName>
// 该方法在父类 AbstractUrlHandlerMapping中实现
registerHandler(urls, beanName);
}
}
if ((logger.isDebugEnabled() && !getHandlerMap().isEmpty()) || logger.isTraceEnabled()) {
logger.debug("Detected " + getHandlerMap().size() + " mappings in " + formatMappingName());
}
}
@Override
public void run(ApplicationArguments applicationArguments) {
LogUtils.info("Aooms("+ Aooms.VERSION +") Start Sucess, At " + DateUtil.now());
ApplicationContext context = SpringUtils.getApplicationContext();
ServiceConfigurations serviceConfigurations = context.getBean(ServiceConfigurations.class);
AoomsWebMvcConfigurer webMvcConfigurer = (AoomsWebMvcConfigurer) context.getBean("webMvcConfigurer");
String[] beanNames = context.getBeanNamesForType(AoomsSetting.class);
LogUtils.info("SettingBeanNames = " + JSON.toJSONString(beanNames));
for(String name : beanNames){
AoomsSetting settingBean = (AoomsSetting)context.getBean(name);
//settingBean.configInterceptor(webMvcConfigurer.getInterceptorRegistryProxy());
settingBean.configProps(Aooms.self().getPropertyObject());
settingBean.configService(serviceConfigurations);
settingBean.onFinish(Aooms.self());
}
//Set<Class<?>> classes = ClassScaner.scanPackageByAnnotation("net",AoomsSettingBean.class);
//System.err.println(classes.size());
}
@Override
public List<ContentUtilizer> getContentUtilizers() {
ApplicationContext applicationContext = this.getApplicationContext();
String[] defNames = applicationContext.getBeanNamesForType(ContentUtilizer.class);
List<ContentUtilizer> contentUtilizers = new ArrayList<ContentUtilizer>(defNames.length);
for (String defName : defNames) {
Object service = null;
try {
service = applicationContext.getBean(defName);
if (service != null) {
ContentUtilizer contentUtilizer = (ContentUtilizer) service;
contentUtilizers.add(contentUtilizer);
}
} catch (Throwable t) {
_logger.error("error loading ReferencingObject {}", defName, t);
}
}
return contentUtilizers;
}
@Override
public <T> Provider<T> provider(Injector injector, Key<T> key)
{
Class<?> type = key.rawClass();
if (ApplicationContext.class.equals(type)) {
return null;
}
ApplicationContext context = context(injector);
if (context == null) {
return null;
}
String[] names = context.getBeanNamesForType(type);
if (names == null || names.length == 0) {
return null;
}
return ()->(T) context.getBean(type);
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
log.debug("setAC: " + context.getDisplayName());
String[] autobeans = context.getBeanNamesForType(AutoRegisterEntityProvider.class, false, false);
StringBuilder registeredPrefixes = new StringBuilder();
for (String autobean : autobeans) {
AutoRegisterEntityProvider register = (AutoRegisterEntityProvider) context
.getBean(autobean);
if (register.getEntityPrefix() == null || register.getEntityPrefix().equals("")) {
// should this die here or is this error log enough? -AZ
log.error("Could not autoregister EntityProvider because the enity prefix is null or empty string for class: "
+ register.getClass().getName());
} else {
registeredPrefixes.append(" : " + register.getEntityPrefix());
entityProviderManager.registerEntityProvider(register);
}
}
log.info("AutoRegistered EntityProvider prefixes " + registeredPrefixes);
// TODO - deal with de-registration in the case we ever support dynamic contexts.
}
/**
* Effettua la chiusura dei datasource definiti nel contesto.
*
* @param applicationContext Il contesto dell'applicazione.
* @throws Exception In caso di errore nel recupero o chiusura dei
* DataSource.
*/
public void closeDataSources(ApplicationContext applicationContext) throws Exception {
String[] dataSourceNames = applicationContext.getBeanNamesForType(BasicDataSource.class);
for (int i = 0; i < dataSourceNames.length; i++) {
BasicDataSource dataSource = (BasicDataSource) applicationContext.getBean(dataSourceNames[i]);
if (null != dataSource) {
dataSource.close();
}
}
}
@Override
@SuppressWarnings("unchecked")
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (initialized.compareAndSet(false, true)) {
this.redisTemplate = context.getBean("stringReactiveRedisTemplate", ReactiveRedisTemplate.class);
this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class);
if (context.getBeanNamesForType(Validator.class).length > 0) {
this.setValidator(context.getBean(Validator.class));
}
}
}
@Override
public void afterPropertiesSet() {
if (this.argumentResolvers.getResolvers().isEmpty()) {
this.argumentResolvers.addResolvers(initArgumentResolvers());
}
if (this.returnValueHandlers.getReturnValueHandlers().isEmpty()) {
this.returnValueHandlers.addHandlers(initReturnValueHandlers());
}
Log returnValueLogger = getReturnValueHandlerLogger();
if (returnValueLogger != null) {
this.returnValueHandlers.setLogger(returnValueLogger);
}
this.handlerMethodLogger = getHandlerMethodLogger();
ApplicationContext context = getApplicationContext();
if (context == null) {
return;
}
for (String beanName : context.getBeanNamesForType(Object.class)) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
try {
beanType = context.getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
}
private void configure(H http) {
OptionsEndpointFilter optionsEndpointFilter;
ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
String[] beanNames = applicationContext.getBeanNamesForType(OptionsEndpointFilter.class);
if (beanNames.length == 0) {
optionsEndpointFilter = new OptionsEndpointFilter(optionsProvider, objectConverter);
optionsEndpointFilter.setFilterProcessesUrl(processingUrl);
} else {
optionsEndpointFilter = applicationContext.getBean(OptionsEndpointFilter.class);
}
http.addFilterAfter(optionsEndpointFilter, SessionManagementFilter.class);
}
static <H extends HttpSecurityBuilder<H>> ChallengeRepository getChallengeRepository(H http) {
ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
ChallengeRepository challengeRepository;
String[] beanNames = applicationContext.getBeanNamesForType(ChallengeRepository.class);
if (beanNames.length == 0) {
challengeRepository = new HttpSessionChallengeRepository();
} else {
challengeRepository = applicationContext.getBean(ChallengeRepository.class);
}
return challengeRepository;
}
public static <H extends HttpSecurityBuilder<H>> OptionsProvider getOptionsProvider(H http) {
ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
OptionsProvider optionsProvider;
String[] beanNames = applicationContext.getBeanNamesForType(OptionsProvider.class);
if (beanNames.length == 0) {
WebAuthnUserDetailsService userDetailsService = applicationContext.getBean(WebAuthnUserDetailsService.class);
optionsProvider = new OptionsProviderImpl(userDetailsService, getChallengeRepository(http));
} else {
optionsProvider = applicationContext.getBean(OptionsProvider.class);
}
return optionsProvider;
}
public static <H extends HttpSecurityBuilder<H>> ServerPropertyProvider getServerPropertyProvider(H http) {
ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
ServerPropertyProvider serverPropertyProvider;
String[] beanNames = applicationContext.getBeanNamesForType(ServerPropertyProvider.class);
if (beanNames.length == 0) {
serverPropertyProvider = new ServerPropertyProviderImpl(getOptionsProvider(http), getChallengeRepository(http));
} else {
serverPropertyProvider = applicationContext.getBean(ServerPropertyProvider.class);
}
return serverPropertyProvider;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> beanType, Object... args) {
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
String[] names = context.getBeanNamesForType(beanType);
if (names.length == 0) {
throw new OLATRuntimeException("found no bean name for: " + beanType + ". Calling this method should find one bean name!", null);
} else if (names.length > 1) {
throw new OLATRuntimeException("found more bean names for: " + beanType + ". Calling this method should find one bean name!", null);
}
Object o = context.getBean(names[0], args);
return (T) o;
}
private void checkUiRequestMapping() {
if (this.uiMapping != null)
return;
ApplicationContext ctx = VaadinUtils.getApplicationContext();
String names[] = ctx.getBeanNamesForType(UiRequestMapping.class);
if (names.length > 0) {
this.uiMapping = ctx.getBean(names[0], UiRequestMapping.class);
}
else {
this.uiMapping = new UrlBeanNameUiMapping();
((UrlBeanNameUiMapping) this.uiMapping).init(ctx);
}
}
private void parseCacheDuration(ApplicationContext applicationContext) {
final Map<String, Long> cacheExpires = new HashMap<String, Long>();
String[] beanNames = applicationContext.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
final Class clazz = applicationContext.getType(beanName);
Service service = findAnnotation(clazz, Service.class);
if (null == service) {
continue;
}
addCacheExpires(clazz, cacheExpires);
}
logger.info(cacheExpires.toString());
//设置有效期
super.setExpires(cacheExpires);
}
@SuppressWarnings("unchecked")
public <T> T enhanceTargeter0(ApplicationContext appContext, FeignClientFactoryBean factory, Supplier<T> defaultTarget) {
BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) appContext;
Class<?> fallbackType = factory.getFallback();
Class<?> clientInterface = factory.getType();
// EnhanceFeignClient enhanceAnno = clientInterface.getAnnotation(EnhanceFeignClient.class);
EnhanceFeignClient enhanceAnno = AnnotatedElementUtils.findMergedAnnotation(clientInterface, EnhanceFeignClient.class);
if(enhanceAnno==null || enhanceAnno.local()==void.class){
return defaultTarget.get();
}
// Class<?> apiInterface = enhanceAnno.local()==void.class?clientInterface.getInterfaces()[0]:enhanceAnno.local();//parent interface
Class<?> apiInterface = enhanceAnno.local();
String[] typeBeanNames = appContext.getBeanNamesForType(apiInterface);//maybe: feignclient, fallback, controller
// ApplicationContext app = Springs.getInstance().getAppContext();
if(typeBeanNames.length<=1){
return defaultTarget.get();
}
//排除fallback和FeignClientFactoryBean后,取第一个bean
Optional<String> localBeanNameOpt = Stream.of(typeBeanNames).filter(lbn->{
BeanDefinition bd = bdr.getBeanDefinition(lbn);
return !bd.getBeanClassName().equals(fallbackType.getName()) && !bd.getBeanClassName().equals(FeignClientFactoryBean.class.getName());
})
.findFirst();
if(!localBeanNameOpt.isPresent()){
if(log.isInfoEnabled()){
log.info("local implement not found for feign interface: {}, use default target.", apiInterface);
}
return defaultTarget.get();
}
T localProxy = (T)Proxys.interceptInterface(clientInterface, new SpringBeanMethodInterceptor(appContext, localBeanNameOpt.get()));
if(log.isInfoEnabled()){
log.info("local implement has been found for feign interface: {}, use local bean: {}", apiInterface, localBeanNameOpt.get());
}
return localProxy;
}
/**
* Register all handlers specified in the Portlet mode map for the corresponding modes.
* @throws org.springframework.beans.BeansException if the handler couldn't be registered
*/
protected void detectHandlers() throws BeansException {
ApplicationContext context = getApplicationContext();
String[] beanNames = context.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
Class<?> handlerType = context.getType(beanName);
RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
if (mapping != null) {
// @RequestMapping found at type level
String[] modeKeys = mapping.value();
String[] params = mapping.params();
boolean registerHandlerType = true;
if (modeKeys.length == 0 || params.length == 0) {
registerHandlerType = !detectHandlerMethods(handlerType, beanName, mapping);
}
if (registerHandlerType) {
AbstractParameterMappingPredicate predicate = new TypeLevelMappingPredicate(
params, mapping.headers(), mapping.method());
for (String modeKey : modeKeys) {
registerHandler(new PortletMode(modeKey), beanName, predicate);
}
}
}
else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {
detectHandlerMethods(handlerType, beanName, mapping);
}
}
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
String[] autobeans = context.getBeanNamesForType(EventReceiver.class, false, false);
for (String autobean : autobeans) {
EventReceiver receiver = (EventReceiver) context.getBean(autobean);
if (receiver != null) {
receivers.put(receiver.getClass().getClassLoader(), receiver);
}
}
}