java类org.springframework.beans.factory.config.ConfigurableListableBeanFactory的实例源码

AbstractApplicationContext.java 文件源码 项目:lams 阅读 22 收藏 0 点赞 0 评论 0
/**
 * 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 + "]");
        }
    }
}
DuoMultifactorWebflowConfigurer.java 文件源码 项目:cas-5.1.0 阅读 19 收藏 0 点赞 0 评论 0
@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);
                }
            });
}
GenericScope.java 文件源码 项目:configx 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 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.");
    }

}
BaseActiveStoreConfiguration.java 文件源码 项目:Lagerta 阅读 20 收藏 0 点赞 0 评论 0
/** {@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);
}
AnnotationBean.java 文件源码 项目:EatDubbo 阅读 23 收藏 0 点赞 0 评论 0
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
        }
    }
}
LocDataSourceAutoConfiguration.java 文件源码 项目:loc-framework 阅读 22 收藏 0 点赞 0 评论 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");
}
QuartzJobRegistrarBeanFactoryPostProcessor.java 文件源码 项目:taboola-cronyx 阅读 28 收藏 0 点赞 0 评论 0
@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);
        }
    }
}
RestTemplateFactory.java 文件源码 项目:Persephone 阅读 20 收藏 0 点赞 0 评论 0
/**
 * 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);
    };
}
BeanFactoryAnnotationUtils.java 文件源码 项目:lams 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 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!");
    }
}
DiaowenProperty.java 文件源码 项目:DWSurvey 阅读 20 收藏 0 点赞 0 评论 0
@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);
        }
        */
    }
JerseyResourcesPostProcessor.java 文件源码 项目:holon-jaxrs 阅读 23 收藏 0 点赞 0 评论 0
@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
        }
    }
}
OsgiServiceFactoryBean.java 文件源码 项目:gemini.blueprint 阅读 26 收藏 0 点赞 0 评论 0
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;
}
BeanFactoryUtils.java 文件源码 项目:gemini.blueprint 阅读 23 收藏 0 点赞 0 评论 0
/**
 * 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()]);
}
BeanRegistryUtils.java 文件源码 项目:holon-core 阅读 20 收藏 0 点赞 0 评论 0
/**
 * 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;
}
LazyExporterTest.java 文件源码 项目:gemini.blueprint 阅读 22 收藏 0 点赞 0 评论 0
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);
}
CustomPropertyPlaceholderConfigurer.java 文件源码 项目:teasy 阅读 22 收藏 0 点赞 0 评论 0
@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());
    }
}
OAuth2MethodSecurityConfiguration.java 文件源码 项目:spring-security-oauth2-boot 阅读 22 收藏 0 点赞 0 评论 0
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
        throws BeansException {
    OAuth2ExpressionHandlerInjectionPostProcessor processor = new OAuth2ExpressionHandlerInjectionPostProcessor(
            this.applicationContext);
    beanFactory.addBeanPostProcessor(processor);
}
CseXmlWebApplicationContext.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 27 收藏 0 点赞 0 评论 0
@Override
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  super.invokeBeanFactoryPostProcessors(beanFactory);

  // inject servlet after config installed and before transport init
  RestServletInjector.defaultInject(getServletContext());
  ServletUtils.saveUrlPrefix(getServletContext());
}
MyBeanFactoryPostProcessor.java 文件源码 项目:springboot-analysis 阅读 20 收藏 0 点赞 0 评论 0
@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
        );
    }
}
StubCloudConnectorTest.java 文件源码 项目:spring-cloud-vault-connector 阅读 17 收藏 0 点赞 0 评论 0
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);
        }
    };
}
ConditionEvaluator.java 文件源码 项目:lams 阅读 27 收藏 0 点赞 0 评论 0
private ConfigurableListableBeanFactory deduceBeanFactory(BeanDefinitionRegistry source) {
    if (source instanceof ConfigurableListableBeanFactory) {
        return (ConfigurableListableBeanFactory) source;
    }
    if (source instanceof ConfigurableApplicationContext) {
        return (((ConfigurableApplicationContext) source).getBeanFactory());
    }
    return null;
}
PropertyPlaceholderConfigurer.java 文件源码 项目:ocmall 阅读 27 收藏 0 点赞 0 评论 0
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);
    }

}
FlowController.java 文件源码 项目:spring-web-jsflow 阅读 14 收藏 0 点赞 0 评论 0
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;
}
InitPropertyPlaceholderConfigurer.java 文件源码 项目:validator-web 阅读 15 收藏 0 点赞 0 评论 0
@Override
protected void processProperties(
        ConfigurableListableBeanFactory beanFactoryToProcess,
        Properties props) throws BeansException {
    super.processProperties(beanFactoryToProcess, props);
    this.properties.putAll(props);
}
PropertyPlaceholder.java 文件源码 项目:opencron 阅读 23 收藏 0 点赞 0 评论 0
@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);
    }
}
BeanExtender.java 文件源码 项目:alfresco-repository 阅读 29 收藏 0 点赞 0 评论 0
/**
 * @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());
    }
}
CentralDogmaConfiguration.java 文件源码 项目:centraldogma 阅读 28 收藏 0 点赞 0 评论 0
@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;
}
AbstractRefreshableApplicationContext.java 文件源码 项目:lams 阅读 25 收藏 0 点赞 0 评论 0
@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;
    }
}
CustomAutowireConfigurer.java 文件源码 项目:lams 阅读 23 收藏 0 点赞 0 评论 0
@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);
        }
    }
}
StepsAnnotationProcessor.java 文件源码 项目:martini-core 阅读 18 收藏 0 点赞 0 评论 0
@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();
}


问题


面经


文章

微信
公众号

扫码关注公众号