Java Code Examples for org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBean()
The following examples show how to use
org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBean() .
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: AbstractApplicationContext.java From spring-analysis-note with MIT License | 6 votes |
/** * Initialize the ApplicationEventMulticaster. * Uses SimpleApplicationEventMulticaster if none defined in the context. * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 如有有自己注册class Name 是 applicationEventMulticaster,使用自定义广播器 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 没有自定义,使用默认的事件广播器 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
Example 2
Source File: ServiceRegisterPostProcessorFactory.java From Ratel with Apache License 2.0 | 6 votes |
@SuppressWarnings("PMD.EmptyCatchBlock") public ServiceRegisterPostProcessor create(ConfigurableListableBeanFactory beanFactory, RegisterStrategy registerStrategy) { SelfAddressProviderChain selfAddressProvider = beanFactory.getBean(SelfAddressProviderChain.class); if (selfAddressProvider == null) { throw new IllegalStateException("No SelfAddressProvider bean in context"); } final HostAndPort hostAndPort = selfAddressProvider.getHostAndPort(); ServletContext servletContext = null; try { servletContext = beanFactory.getBean(ServletContext.class); } catch (NoSuchBeanDefinitionException e) { } final String contextRoot = servletContext != null ? servletContext.getContextPath() : ""; final String address = String .format("http://%s:%s%s%s", hostAndPort.getHostText(), hostAndPort.getPort(), contextRoot, RATEL_PATH); return new ServiceRegisterPostProcessor(beanFactory, registerStrategy, address); }
Example 3
Source File: AbstractApplicationContext.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Initialize the ApplicationEventMulticaster. * Uses SimpleApplicationEventMulticaster if none defined in the context. * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnabled()) { logger.debug("Unable to locate ApplicationEventMulticaster with name '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default [" + this.applicationEventMulticaster + "]"); } } }
Example 4
Source File: BeanFactoryAnnotationUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier). * @param bf the BeanFactory to get the target bean from * @param beanType the type of bean to retrieve * @param qualifier the qualifier for selecting between multiple bean matches * @return the matching bean of type {@code T} (never {@code null}) * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found */ private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) { String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType); String matchingBean = null; for (String beanName : candidateBeans) { if (isQualifierMatch(qualifier, beanName, bf)) { if (matchingBean != null) { throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "'"); } matchingBean = beanName; } } if (matchingBean != null) { return bf.getBean(matchingBean, beanType); } else if (bf.containsBean(qualifier)) { // Fallback: target bean at least found by bean name - probably a manually registered singleton. return bf.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!"); } }
Example 5
Source File: ConfigBeanFactoryPostProcessor.java From ace with Apache License 2.0 | 6 votes |
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { Iterator<String> iterator = configurableListableBeanFactory.getBeanNamesIterator(); while (iterator.hasNext()) { Object obj = configurableListableBeanFactory.getBean(iterator.next()); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if (field.getType().isAnnotationPresent(ConfigBean.class)) { field.setAccessible(true); try { Object value = config.configBeanParser(field.getType()).getConfigBean(); field.set(obj, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } }
Example 6
Source File: RegistryBeanProviderFactory.java From Ratel with Apache License 2.0 | 6 votes |
public RegistryStrategiesProvider create(ConfigurableListableBeanFactory beanFactory) { final Environment environment = beanFactory.getBean(Environment.class); if ("false".equals(environment.getProperty(RatelContextApplier.SERVICE_DISCOVERY_ENABLED))) { LOGGER.info("Ratel is disabled"); return null; } LOGGER.info("Ratel is enabled"); RegistryStrategiesProvider registryBeanProvider; try { registryBeanProvider = beanFactory.getBean(RegistryStrategiesProvider.class); LOGGER.info("Ratel was already configured, skiping second initialization"); } catch (NoSuchBeanDefinitionException e) { registryBeanProvider = createAndRegisterStrategiesProvider(beanFactory); LOGGER.info("Ratel is configured"); } return registryBeanProvider; }
Example 7
Source File: MultiPropertyPlaceholderConfigurer.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
@Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); @SuppressWarnings("unchecked") HashMap<String, String> urls = (HashMap<String, String>) beanFactoryToProcess.getBean("urls"); for (Object key : props.keySet()) { if (key != null && key instanceof String) { String keyName = (String) key; if (keyName.endsWith("_url")) { Object value = props.get(keyName); if (value != null) { urls.put(keyName, value.toString()); } } } } }
Example 8
Source File: AbstractApplicationContext.java From java-technology-stack with MIT License | 6 votes |
/** * Initialize the LifecycleProcessor. * Uses DefaultLifecycleProcessor if none defined in the context. * @see org.springframework.context.support.DefaultLifecycleProcessor */ protected void initLifecycleProcessor() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) { this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class); if (logger.isTraceEnabled()) { logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]"); } } else { DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); this.lifecycleProcessor = defaultProcessor; beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor); if (logger.isTraceEnabled()) { logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " + "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]"); } } }
Example 9
Source File: AbstractApplicationContext.java From java-technology-stack with MIT License | 6 votes |
/** * Initialize the ApplicationEventMulticaster. * Uses SimpleApplicationEventMulticaster if none defined in the context. * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
Example 10
Source File: EnvironmentBeanFactoryPostProcessor.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { StandardEnvironment environment = (StandardEnvironment) beanFactory.getBean(Environment.class); if (environment != null) { Map<String, Object> systemEnvironment = environment.getSystemEnvironment(); Map<String, Object> prefixlessSystemEnvironment = new HashMap<>(systemEnvironment.size()); systemEnvironment .keySet() .forEach(key -> { String prefixKey = key; for (String propertyPrefix : PROPERTY_PREFIXES) { if (key.startsWith(propertyPrefix)) { prefixKey = key.substring(propertyPrefix.length()); break; } } prefixlessSystemEnvironment.put(prefixKey, systemEnvironment.get(key)); }); environment.getPropertySources().replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new RelaxedPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, prefixlessSystemEnvironment)); } }
Example 11
Source File: AbstractApplicationContext.java From spring-analysis-note with MIT License | 6 votes |
/** * Initialize the LifecycleProcessor. * Uses DefaultLifecycleProcessor if none defined in the context. * @see org.springframework.context.support.DefaultLifecycleProcessor */ protected void initLifecycleProcessor() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) { this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class); if (logger.isTraceEnabled()) { logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]"); } } else { DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); this.lifecycleProcessor = defaultProcessor; beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor); if (logger.isTraceEnabled()) { logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " + "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]"); } } }
Example 12
Source File: IOCContainerAppUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() { Resource res = new ClassPathResource("ioc-container-difference-example.xml"); ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); beanFactoryPostProcessor.postProcessBeanFactory(factory); assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); factory.addBeanPostProcessor(beanPostProcessor); Student student = (Student) factory.getBean("student"); assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); }
Example 13
Source File: RegisterZipkinHealthIndicators.java From pivotal-bank-demo with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (!(event instanceof ApplicationReadyEvent)) return; ConfigurableListableBeanFactory beanFactory = ((ApplicationReadyEvent) event).getApplicationContext().getBeanFactory(); ZipkinHealthIndicator healthIndicator = beanFactory.getBean(ZipkinHealthIndicator.class); for (Component component : beanFactory.getBeansOfType(Component.class).values()) { healthIndicator.addComponent(component); } }
Example 14
Source File: DubboConfigBeanDefinitionConflictProcessor.java From dubbo-spring-boot-project with Apache License 2.0 | 5 votes |
/** * Resolve the unique {@link ApplicationConfig} Bean * * @param registry {@link BeanDefinitionRegistry} instance * @param beanFactory {@link ConfigurableListableBeanFactory} instance * @see EnableDubboConfig */ private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) { this.environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class); String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately. return; } // Remove ApplicationConfig Beans that are configured by "dubbo.application.*" Stream.of(beansNames) .filter(this::isConfiguredApplicationConfigBeanName) .forEach(registry::removeBeanDefinition); beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length > 1) { throw new IllegalStateException(String.format("There are more than one instances of %s, whose bean definitions : %s", ApplicationConfig.class.getSimpleName(), Stream.of(beansNames) .map(registry::getBeanDefinition) .collect(Collectors.toList())) ); } }
Example 15
Source File: AbstractApplicationContext.java From java-technology-stack with MIT License | 5 votes |
/** * Initialize the MessageSource. * Use parent's if none defined in this context. */ protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
Example 16
Source File: DisableEndpointPostProcessor.java From edison-microservice with Apache License 2.0 | 5 votes |
private void disableEndpoint(final ConfigurableListableBeanFactory beanFactory) { final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class); final MutablePropertySources propertySources = env.getPropertySources(); propertySources.addFirst( new MapPropertySource(endpoint + "PropertySource", singletonMap("endpoints." + endpoint + ".enabled", false)) ); }
Example 17
Source File: VaultPropertySourceRegistrar.java From spring-vault with Apache License 2.0 | 5 votes |
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class); MutablePropertySources propertySources = env.getPropertySources(); registerPropertySources( beanFactory.getBeansOfType(org.springframework.vault.core.env.VaultPropertySource.class).values(), propertySources); registerPropertySources(beanFactory .getBeansOfType(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class).values(), propertySources); }
Example 18
Source File: AbstractApplicationContext.java From spring-analysis-note with MIT License | 5 votes |
/** * Initialize the MessageSource. * Use parent's if none defined in this context. */ protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
Example 19
Source File: DsRouterRegistrar.java From onetwo with Apache License 2.0 | 4 votes |
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { DatasourceRouterProperties ds = beanFactory.getBean(DatasourceRouterProperties.class); System.out.println("test:"+datasourceRouterProperties); }
Example 20
Source File: LocMybatisAutoConfiguration.java From loc-framework with MIT License | 4 votes |
private @Nullable SqlSessionFactory createSqlSessionFactory( ConfigurableListableBeanFactory configurableListableBeanFactory, String prefixName, MybatisProperties mybatisProperties) { DataSource dataSource = configurableListableBeanFactory .getBean(prefixName + "Ds", DataSource.class); MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setVfs(LocSpringBootVFS.class); Optional.ofNullable(mybatisProperties.getConfigLocation()).map(this.resourceLoader::getResource) .ifPresent(sqlSessionFactoryBean::setConfigLocation); org.apache.ibatis.session.Configuration configuration = mybatisProperties.getConfiguration(); if (configuration == null && !StringUtils.hasText(mybatisProperties.getConfigLocation())) { configuration = new org.apache.ibatis.session.Configuration(); } sqlSessionFactoryBean.setConfiguration(configuration); Optional.ofNullable(mybatisProperties.getConfigurationProperties()) .ifPresent(sqlSessionFactoryBean::setConfigurationProperties); Optional.ofNullable(mybatisProperties.getTypeAliasesPackage()) .ifPresent(sqlSessionFactoryBean::setTypeAliasesPackage); Optional.ofNullable(mybatisProperties.getTypeHandlersPackage()) .ifPresent(sqlSessionFactoryBean::setTypeHandlersPackage); if (!ObjectUtils.isEmpty(mybatisProperties.resolveMapperLocations())) { sqlSessionFactoryBean.setMapperLocations(mybatisProperties.resolveMapperLocations()); } PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); sqlSessionFactoryBean.setPlugins(new Interceptor[]{paginationInterceptor}); try { SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject(); if (sqlSessionFactory == null) { log.error("sqlSessionFactoryBean get object is null"); return null; } register(configurableListableBeanFactory, sqlSessionFactory, prefixName + "SessionFactory", prefixName + "Sf"); if (!Strings.isNullOrEmpty(mybatisProperties.getBasePackage())) { createBasePackageScanner((BeanDefinitionRegistry) configurableListableBeanFactory, mybatisProperties.getBasePackage(), prefixName); } else { createClassPathMapperScanner((BeanDefinitionRegistry) configurableListableBeanFactory, prefixName); } return sqlSessionFactory; } catch (Exception e) { log.error(e.getMessage(), e); } return null; }