Java Code Examples for org.springframework.context.ApplicationContext#getBeanNamesForType()
The following examples show how to use
org.springframework.context.ApplicationContext#getBeanNamesForType() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EntityProviderAutoRegistrar.java From sakai with Educational Community License v2.0 | 6 votes |
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. }
Example 2
Source File: MainTest.java From code with Apache License 2.0 | 6 votes |
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); } }
Example 3
Source File: IncludeSpring.java From baratine with GNU General Public License v2.0 | 6 votes |
@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); }
Example 4
Source File: AbstractDetectingUrlHandlerMapping.java From java-technology-stack with MIT License | 6 votes |
/** * 建立当前 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()); } }
Example 5
Source File: AoomsApplicationRunner.java From Aooms with Apache License 2.0 | 6 votes |
@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()); }
Example 6
Source File: ContentHelper.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
@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; }
Example 7
Source File: EntityProviderAutoRegistrar.java From sakai with Educational Community License v2.0 | 6 votes |
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. }
Example 8
Source File: WebAuthnConfigurerUtil.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
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; }
Example 9
Source File: EventReceiverCoordinator.java From sakai with Educational Community License v2.0 | 5 votes |
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); } } }
Example 10
Source File: DefaultAnnotationHandlerMapping.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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); } } }
Example 11
Source File: LocalTargeterEnhancer.java From onetwo with Apache License 2.0 | 5 votes |
@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; }
Example 12
Source File: SpringRedisCacheManager.java From Mykit with Apache License 2.0 | 5 votes |
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); }
Example 13
Source File: SpringUIProvider.java From jdal with Apache License 2.0 | 5 votes |
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); } }
Example 14
Source File: CoreSpringFactory.java From olat with Apache License 2.0 | 5 votes |
@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; }
Example 15
Source File: WebAuthnConfigurerUtil.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
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; }
Example 16
Source File: WebAuthnConfigurerUtil.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
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; }
Example 17
Source File: WebAuthnLoginConfigurer.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
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); }
Example 18
Source File: AbstractMethodMessageHandler.java From java-technology-stack with MIT License | 5 votes |
@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); } } } }
Example 19
Source File: RateCheckRedisRateLimiter.java From momo-cloud-permission with Apache License 2.0 | 5 votes |
@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)); } } }
Example 20
Source File: ConfigTestUtils.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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(); } } }