/** * 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 + "]"); } } }
@Override protected void doInitialize() throws Exception { provider.getProviders().forEach(p -> { final FlowDefinitionRegistry duoFlowRegistry = buildDuoFlowRegistry(p); applicationContext.getAutowireCapableBeanFactory().initializeBean(duoFlowRegistry, p.getId()); final ConfigurableListableBeanFactory cfg = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory(); cfg.registerSingleton(p.getId(), duoFlowRegistry); registerMultifactorProviderAuthenticationWebflow(getLoginFlow(), p.getId(), duoFlowRegistry); }); casProperties.getAuthn().getMfa().getDuo() .stream() .filter(MultifactorAuthenticationProperties.Duo::isTrustedDeviceEnabled) .forEach(duo -> { final String id = duo.getId(); try { LOGGER.debug("Activating multifactor trusted authentication for webflow [{}]", id); final FlowDefinitionRegistry registry = applicationContext.getBean(id, FlowDefinitionRegistry.class); registerMultifactorTrustedAuthentication(registry); } catch (final Exception e) { LOGGER.error("Failed to register multifactor trusted authentication for " + id, e); } }); }
/** * If the bean factory is a DefaultListableBeanFactory then it can serialize scoped * beans and deserialize them in another context (even in another JVM), as long as the * ids of the bean factories match. This method sets up the serialization id to be * either the id provided to the scope instance, or if that is null, a hash of all the * bean names. * * @param beanFactory the bean factory to configure */ private void setSerializationId(ConfigurableListableBeanFactory beanFactory) { if (beanFactory instanceof DefaultListableBeanFactory) { String id = this.id; if (id == null) { List<String> list = new ArrayList<>( Arrays.asList(beanFactory.getBeanDefinitionNames())); Collections.sort(list); String names = list.toString(); logger.debug("Generating bean factory id from names: " + names); id = UUID.nameUUIDFromBytes(names.getBytes()).toString(); } logger.info("BeanFactory id=" + id); ((DefaultListableBeanFactory) beanFactory).setSerializationId(id); } else { logger.warn("BeanFactory was not a DefaultListableBeanFactory, so RefreshScope beans " + "cannot be serialized reliably and passed to a remote JVM."); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void postProcessBeanFactory( ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { String[] igniteConfigNames = configurableListableBeanFactory.getBeanNamesForType(IgniteConfiguration.class); if (igniteConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one ignite configuration!"); } String[] activeStoreConfigNames = configurableListableBeanFactory.getBeanNamesForType(BaseActiveStoreConfiguration.class); if (activeStoreConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one active store configuration!"); } BeanDefinition igniteConfigDef = configurableListableBeanFactory.getBeanDefinition(igniteConfigNames[0]); MutablePropertyValues propertyValues = igniteConfigDef.getPropertyValues(); if (!propertyValues.contains(USER_ATTRS_PROP_NAME)) { propertyValues.add(USER_ATTRS_PROP_NAME, new ManagedMap()); } PropertyValue propertyValue = propertyValues.getPropertyValue(USER_ATTRS_PROP_NAME); Map userAttrs = (Map)propertyValue.getValue(); TypedStringValue key = new TypedStringValue(CONFIG_USER_ATTR); RuntimeBeanReference value = new RuntimeBeanReference(beanName); userAttrs.put(key, value); }
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (annotationPackage == null || annotationPackage.length() == 0) { return; } if (beanFactory instanceof BeanDefinitionRegistry) { try { // init scanner Class<?> scannerClass = ReflectUtils.forName("org.springframework.context.annotation.ClassPathBeanDefinitionScanner"); Object scanner = scannerClass.getConstructor(new Class<?>[] {BeanDefinitionRegistry.class, boolean.class}).newInstance(new Object[] {(BeanDefinitionRegistry) beanFactory, true}); // add filter Class<?> filterClass = ReflectUtils.forName("org.springframework.core.type.filter.AnnotationTypeFilter"); Object filter = filterClass.getConstructor(Class.class).newInstance(Service.class); Method addIncludeFilter = scannerClass.getMethod("addIncludeFilter", ReflectUtils.forName("org.springframework.core.type.filter.TypeFilter")); addIncludeFilter.invoke(scanner, filter); // scan packages String[] packages = Constants.COMMA_SPLIT_PATTERN.split(annotationPackage); Method scan = scannerClass.getMethod("scan", new Class<?>[]{String[].class}); scan.invoke(scanner, new Object[] {packages}); } catch (Throwable e) { // spring 2.0 } } }
private void createBean(ConfigurableListableBeanFactory configurableListableBeanFactory, String prefixName, JdbcProperties jdbcProperties) { String jdbcUrl = jdbcProperties.getJdbcUrl(); checkArgument(!Strings.isNullOrEmpty(jdbcUrl), prefixName + " url is null or empty"); log.info("prefixName is {}, jdbc properties is {}", prefixName, jdbcProperties); HikariDataSource hikariDataSource = createHikariDataSource(jdbcProperties); DataSourceSpy dataSource = new DataSourceSpy(hikariDataSource); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); AnnotationTransactionAspect.aspectOf().setTransactionManager(transactionManager); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); register(configurableListableBeanFactory, dataSource, prefixName + "DataSource", prefixName + "Ds"); register(configurableListableBeanFactory, jdbcTemplate, prefixName + "JdbcTemplate", prefixName + "Jt"); register(configurableListableBeanFactory, transactionManager, prefixName + "TransactionManager", prefixName + "Tx"); }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanNames = beanFactory.getBeanNamesForAnnotation(Job.class); for(String name : beanNames){ JobDetail jobDetail = buildJobForBeanFactory(beanFactory, name); if (jobDetail == null){ logger.warn("could not load JobDetail for {}", name); continue; } try { scheduler.addJob(jobDetail, true); } catch (SchedulerException e) { throw new BeanInitializationException("SchedulerException when adding job to scheduler", e); } } }
/** * register specific RestTemplate in Spring Application Context if needed */ private Consumer<Application> createRestTemplateBasicAuth(ConfigurableListableBeanFactory registry) { return app -> { // Create rest template instance RestTemplate restTemplateBasicAuth = defaultRestTemplateConfig.restTemplate(requestFactory, Arrays.asList(defaultRestTemplateConfig.getDefaultAcceptHeader(), MediaType.ALL)); // Configure it with BASIC auth restTemplateBasicAuth.getInterceptors().add(new BasicAuthorizationInterceptor(app.getActuatorUsername(), app.getActuatorPassword())); LOGGER.info("Registered RestTemplate with BASIC auth for application with id {}", app.getId()); // Add bean in Spring application context registry.registerSingleton(getRestTemplateBeanName(app), restTemplateBasicAuth); }; }
/** * 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) { Map<String, T> candidateBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, beanType); T matchingBean = null; for (String beanName : candidateBeans.keySet()) { if (isQualifierMatch(qualifier, beanName, bf)) { if (matchingBean != null) { throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "'"); } matchingBean = candidateBeans.get(beanName); } } if (matchingBean != null) { return matchingBean; } 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!"); } }
@Override protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); DWSTORAGETYPE = props.getProperty("dw.storage.type"); ACCESS_KEY_ID = props.getProperty("dw.yunos.access_keyid"); SECRET_ACCESS_KEY = props.getProperty("dw.yunos.access_keysecret"); ENDPOINT = props.getProperty("dw.yunos.endpoint"); // FILE_BACKET_DOMAIN = props.getProperty("dw.yunos.file_backet_domain"); STORAGE_URL_PREFIX = props.getProperty("dw.storage.url_prefix"); WENJUANHTML_BACKET = props.getProperty("dw.yunos.wenjuan_html_backet"); UPLOADFILE_BACKET = props.getProperty("dw.yunos.upload_file_backet"); UPLOADFILE_JM_BACKET = props.getProperty("dw.yunos.upload_file_jm_backet"); /* ctxPropertiesMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } */ }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { LOGGER.debug(() -> "Lookup @Path and @Provider JAX-RS resource in bean factory [" + beanFactory + "]"); resources = new ArrayList<>(); for (String name : beanFactory.getBeanDefinitionNames()) { try { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (!definition.isAbstract()) { Class<?> beanClass = BeanRegistryUtils.getBeanClass(name, definition, beanFactory, classLoader); if (beanClass != null) { if (isJaxrsResourceClass(definition, beanClass)) { resources.add(new WeakReference<>(beanClass)); LOGGER.debug(() -> "Found JAX-RS resource class: [" + beanClass.getName() + "]"); } } } } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) { // ignore } } }
private boolean isBeanBundleScoped() { boolean bundleScoped = false; // if we do have a bundle scope, use ServiceFactory decoration if (targetBeanName != null) { if (beanFactory instanceof ConfigurableListableBeanFactory) { String beanScope = ((ConfigurableListableBeanFactory) beanFactory).getMergedBeanDefinition(targetBeanName) .getScope(); bundleScoped = OsgiBundleScope.SCOPE_NAME.equals(beanScope); } else // if for some reason, the passed in BeanFactory can't be // queried for scopes and we do // have a bean reference, apply scoped decoration. bundleScoped = true; } return bundleScoped; }
/** * Return all beans depending directly or indirectly (transitively), on the bean identified by the beanName. When * dealing with a FactoryBean, the factory itself can be returned or its product. Additional filtering can be * executed through the type parameter. If no filtering is required, then null can be passed. * * Note that depending on #rawFactoryBeans parameter, the type of the factory or its product can be used when doing * the filtering. * * @param beanFactory beans bean factory * @param beanName root bean name * @param rawFactoryBeans consider the factory bean itself or the its product * @param type type of the beans returned (null to return all beans) * @return bean names */ public static String[] getTransitiveDependenciesForBean(ConfigurableListableBeanFactory beanFactory, String beanName, boolean rawFactoryBeans, Class<?> type) { Assert.notNull(beanFactory); Assert.hasText(beanName); Assert.isTrue(beanFactory.containsBean(beanName), "no bean by name [" + beanName + "] can be found"); Set<String> beans = new LinkedHashSet<String>(8); // used to break cycles between nested beans Set<String> innerBeans = new LinkedHashSet<String>(4); getTransitiveBeans(beanFactory, beanName, rawFactoryBeans, beans, innerBeans); if (type != null) { // filter by type for (Iterator<String> iter = beans.iterator(); iter.hasNext();) { String bean = iter.next(); if (!beanFactory.isTypeMatch(bean, type)) { iter.remove(); } } } return beans.toArray(new String[beans.size()]); }
/** * Get the Factory class name which corresponds to given bean definition. * @param definition Bean definition * @param beanFactory Bean factory * @return Factory class name, or <code>null</code> if not found */ private static String getBeanFactoryClassName(BeanDefinition definition, ConfigurableListableBeanFactory beanFactory) { if (definition instanceof AnnotatedBeanDefinition) { return ((AnnotatedBeanDefinition) definition).getMetadata().getClassName(); } else { if (definition.getFactoryBeanName() != null) { BeanDefinition fd = beanFactory.getBeanDefinition(definition.getFactoryBeanName()); if (fd != null) { return fd.getBeanClassName(); } } else { return definition.getBeanClassName(); } } return null; }
protected void setUp() throws Exception { bundleContext = new MockBundleContext(); context = new GenericApplicationContext(); context.setClassLoader(getClass().getClassLoader()); context.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext)); context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.addPropertyEditorRegistrar(new BlueprintEditorRegistrar()); } }); reader = new XmlBeanDefinitionReader(context); reader.setDocumentLoader(new PublicBlueprintDocumentLoader()); reader.loadBeanDefinitions(new ClassPathResource(CONFIG, getClass())); context.refresh(); blueprintContainer = new SpringBlueprintContainer(context); }
@Override protected void processProperties(final ConfigurableListableBeanFactory beanFactoryToProcess, final Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); properties = props; for (final Map.Entry entry : properties.entrySet()) { resolveSubstitution((String) entry.getKey(), (String) entry.getValue()); } }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { OAuth2ExpressionHandlerInjectionPostProcessor processor = new OAuth2ExpressionHandlerInjectionPostProcessor( this.applicationContext); beanFactory.addBeanPostProcessor(processor); }
@Override protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { super.invokeBeanFactoryPostProcessors(beanFactory); // inject servlet after config installed and before transport init RestServletInjector.defaultInject(getServletContext()); ServletUtils.saveUrlPrefix(getServletContext()); }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("------ register custom bean in BeanFactoryPostProcessor"); beanFactory.registerSingleton("createByBeanFactoryPostProcessor", new SimpleBeanInBeanFactoryPostProcessor()); if(beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionReaderUtils.registerBeanDefinition( new BeanDefinitionHolder(new AnnotatedGenericBeanDefinition(SimpleBeanWithDefinitionInBeanFactoryPostProcessor.class), "simpleBeanWithDefinitionInBeanFactoryPostProcessor"), (BeanDefinitionRegistry) beanFactory ); } }
protected ApplicationContext getTestApplicationContext(Class<?> configClass, ServiceInfo... serviceInfos) { final CloudConnector stubCloudConnector = CloudTestUtil .getTestCloudConnector(serviceInfos); return new AnnotationConfigApplicationContext(configClass) { @Override protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { CloudFactory cloudFactory = new CloudFactory(); cloudFactory.registerCloudConnector(stubCloudConnector); getBeanFactory().registerSingleton(MOCK_CLOUD_BEAN_NAME, cloudFactory); super.prepareBeanFactory(beanFactory); } }; }
private ConfigurableListableBeanFactory deduceBeanFactory(BeanDefinitionRegistry source) { if (source instanceof ConfigurableListableBeanFactory) { return (ConfigurableListableBeanFactory) source; } if (source instanceof ConfigurableApplicationContext) { return (((ConfigurableApplicationContext) source).getBeanFactory()); } return null; }
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); ctxPropertiesMap = new HashMap(); Iterator i$ = props.keySet().iterator(); while(i$.hasNext()) { Object key = i$.next(); String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } }
public static ScriptStorage createDefaultScriptStorage(final ApplicationContext ctx) throws Exception { ScriptStorage scriptStorage = BeanFactoryUtilsEx.beanOfTypeIncludingAncestors(ctx, ScriptStorage.class); if (scriptStorage == null) { scriptStorage = new ScriptStorage(); scriptStorage.setResourceLoader(ctx); scriptStorage.afterPropertiesSet(); if (ctx instanceof ConfigurableApplicationContext) { final ConfigurableListableBeanFactory bf = ((ConfigurableApplicationContext) ctx).getBeanFactory(); bf.registerSingleton("scriptStorage", scriptStorage); } } return scriptStorage; }
@Override protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); this.properties.putAll(props); }
@Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); properties.put(keyStr, value); } }
/** * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { ParameterCheck.mandatory("beanName", beanName); ParameterCheck.mandatory("extendingBeanName", extendingBeanName); // check for bean name if (!beanFactory.containsBean(beanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended."); } // check for extending bean if (!beanFactory.containsBean(extendingBeanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName + "' that is going to extend original bean definition."); } // get the bean definitions BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName); // update class if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName()) && !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName())) { beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName()); } // update properties MutablePropertyValues properties = beanDefinition.getPropertyValues(); MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues(); for (PropertyValue propertyValue : extendingProperties.getPropertyValueList()) { properties.add(propertyValue.getName(), propertyValue.getValue()); } }
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); final String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, ClientFactory.class); for (String beanName : beanNames) { if (hasQualifier(beanFactory, beanName)) { return false; } } return true; }
@Override public final ConfigurableListableBeanFactory getBeanFactory() { synchronized (this.beanFactoryMonitor) { if (this.beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return this.beanFactory; } }
@Override @SuppressWarnings("unchecked") public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.customQualifierTypes != null) { if (!(beanFactory instanceof DefaultListableBeanFactory)) { throw new IllegalStateException( "CustomAutowireConfigurer needs to operate on a DefaultListableBeanFactory"); } DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; if (!(dlbf.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) { dlbf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); } QualifierAnnotationAutowireCandidateResolver resolver = (QualifierAnnotationAutowireCandidateResolver) dlbf.getAutowireCandidateResolver(); for (Object value : this.customQualifierTypes) { Class<? extends Annotation> customType = null; if (value instanceof Class) { customType = (Class<? extends Annotation>) value; } else if (value instanceof String) { String className = (String) value; customType = (Class<? extends Annotation>) ClassUtils.resolveClassName(className, this.beanClassLoader); } else { throw new IllegalArgumentException( "Invalid value [" + value + "] for custom qualifier type: needs to be Class or String."); } if (!Annotation.class.isAssignableFrom(customType)) { throw new IllegalArgumentException( "Qualifier type [" + customType.getName() + "] needs to be annotation type"); } resolver.addQualifierType(customType); } } }
@Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory(); checkState(ConfigurableListableBeanFactory.class.isInstance(beanFactory), "Martini requires the use of a ConfigurableListableBeanFactory"); ConfigurableListableBeanFactory configurable = ConfigurableListableBeanFactory.class.cast(beanFactory); callbacks = ImmutableList.<ReflectionUtils.MethodCallback>builder() .add(new MartiniAnnotationCallback<>(Given.class, GivenContainer.class, configurable)) .add(new MartiniAnnotationCallback<>(And.class, AndContainer.class, configurable)) .add(new MartiniAnnotationCallback<>(When.class, WhenContainer.class, configurable)) .add(new MartiniAnnotationCallback<>(Then.class, ThenContainer.class, configurable)) .build(); }
/** * Check whether the given bean definition is not subject to the annotation-based * required property check as performed by this post-processor. * <p>The default implementations check for the presence of the * {@link #SKIP_REQUIRED_CHECK_ATTRIBUTE} attribute in the bean definition, if any. * It also suggests skipping in case of a bean definition with a "factory-bean" * reference set, assuming that instance-based factories pre-populate the bean. * @param beanFactory the BeanFactory to check against * @param beanName the name of the bean to check against * @return {@code true} to skip the bean; {@code false} to process it */ protected boolean shouldSkip(ConfigurableListableBeanFactory beanFactory, String beanName) { if (beanFactory == null || !beanFactory.containsBeanDefinition(beanName)) { return false; } BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if (beanDefinition.getFactoryBeanName() != null) { return true; } Object value = beanDefinition.getAttribute(SKIP_REQUIRED_CHECK_ATTRIBUTE); return (value != null && (Boolean.TRUE.equals(value) || Boolean.valueOf(value.toString()))); }
protected JobDetail buildJobForBeanFactory(ConfigurableListableBeanFactory beanFactory, String jobBeanName) { try { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(jobBeanName); Class beanClass = Class.forName(beanDefinition.getBeanClassName()); JobDefinition jobDefinition = jobIntrospecter.getJobDefinitionForInstance(beanClass); JobDataMap jdm = new JobDataMap(); jdm.put(Constants.JOB_CRONYX_MARKER, true); jdm.put(Constants.JOB_BEAN_NAME, jobBeanName); jdm.put(Constants.JOB_DEFINITION, jobDefinition); return JobBuilder.newJob() .withIdentity(jobDefinition.getKey().getName(), jobDefinition.getKey().getGroup()) .withDescription(jobDefinition.getDescription()) .ofType(jobClassSelector.select(jobDefinition)) .usingJobData(jdm) .storeDurably() .requestRecovery(jobDefinition.isRecoverable()) .build(); }catch (Exception e) { logger.error("problem creating job detail, logging and going on. ", e); return null; } }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] autoInitBeanNames = beanFactory.getBeanNamesForType(AbstractCacheAutoInit.class, false, false); if (autoInitBeanNames != null) { BeanDefinition bd = beanFactory.getBeanDefinition(JetCacheAutoConfiguration.GLOBAL_CACHE_CONFIG_NAME); String[] dependsOn = bd.getDependsOn(); if (dependsOn == null) { dependsOn = new String[0]; } int oldLen = dependsOn.length; dependsOn = Arrays.copyOf(dependsOn, dependsOn.length + autoInitBeanNames.length); System.arraycopy(autoInitBeanNames,0, dependsOn, oldLen, autoInitBeanNames.length); bd.setDependsOn(dependsOn); } }
@Override public void setBeanFactory(BeanFactory beanFactory) { Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; }
private List<String> getPrimaryBeans(ConfigurableListableBeanFactory beanFactory, List<String> beanNames, boolean considerHierarchy) { List<String> primaryBeans = new ArrayList<String>(); for (String beanName : beanNames) { BeanDefinition beanDefinition = findBeanDefinition(beanFactory, beanName, considerHierarchy); if (beanDefinition != null && beanDefinition.isPrimary()) { primaryBeans.add(beanName); } } return primaryBeans; }
private BeanDefinition findBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName, boolean considerHierarchy) { if (beanFactory.containsBeanDefinition(beanName)) { return beanFactory.getBeanDefinition(beanName); } if (considerHierarchy && beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory()), beanName, considerHierarchy); } return null; }
private Class<?> getConfigurationClassFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, String name) throws Exception { Method method = getFactoryMethod(beanFactory, definition); Class<?> generic = ResolvableType.forMethodReturnType(method).as(FactoryBean.class).resolveGeneric(); if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; }
private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) throws Exception { if (definition instanceof AnnotatedBeanDefinition) { MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata(); if (factoryMethodMetadata instanceof StandardMethodMetadata) { return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod(); } } BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName()); Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(), beanFactory.getBeanClassLoader()); return getFactoryMethod(definition, factoryClass); }
private Class<?> getDirectFactoryBeanGeneric( ConfigurableListableBeanFactory beanFactory, BeanDefinition definition, String name) throws ClassNotFoundException, LinkageError { Class<?> factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader()); Class<?> generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class).resolveGeneric(); if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; }
/** * Check whether the named bean declares a qualifier of the given name. * @param qualifier the qualifier to match * @param beanName the name of the candidate bean * @param bf the {@code BeanFactory} from which to retrieve the named bean * @return {@code true} if either the bean definition (in the XML case) * or the bean's factory method (in the {@code @Bean} case) defines a matching * qualifier value (through {@code <qualifier>} or {@code @Qualifier}) */ private static boolean isQualifierMatch(String qualifier, String beanName, ConfigurableListableBeanFactory bf) { if (bf.containsBean(beanName)) { try { BeanDefinition bd = bf.getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName()); if ((candidate != null && qualifier.equals(candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY))) || qualifier.equals(beanName) || ObjectUtils.containsElement(bf.getAliases(beanName), qualifier)) { return true; } } if (bd instanceof RootBeanDefinition) { Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod(); if (factoryMethod != null) { Qualifier targetAnnotation = factoryMethod.getAnnotation(Qualifier.class); if (targetAnnotation != null && qualifier.equals(targetAnnotation.value())) { return true; } } } } catch (NoSuchBeanDefinitionException ex) { // Ignore - can't compare qualifiers for a manually registered singleton object } } return false; }