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

AbstractBeanFactory.java 文件源码 项目:lams 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
    Assert.notNull(otherFactory, "BeanFactory must not be null");
    setBeanClassLoader(otherFactory.getBeanClassLoader());
    setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
    setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
    if (otherFactory instanceof AbstractBeanFactory) {
        AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
        this.customEditors.putAll(otherAbstractFactory.customEditors);
        this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
        this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
        this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
                otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
        this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
                otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
        this.scopes.putAll(otherAbstractFactory.scopes);
        this.securityContextProvider = otherAbstractFactory.securityContextProvider;
    }
    else {
        setTypeConverter(otherFactory.getTypeConverter());
    }
}
AnnotationRelationshipDetector.java 文件源码 项目:cereebro 阅读 23 收藏 0 点赞 0 评论 0
/**
 * Detect relationships in annotated {@link Bean @Bean} Factory methods.
 * 
 * @return Relationships detected from factory methods.
 */
protected Set<Relationship> detectAnnotatedFactoryMethods() {
    Set<Relationship> result = new HashSet<>();
    /* retrieve all beans declared in the application context */
    String[] annotateBeans = applicationContext.getBeanDefinitionNames();
    ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
    for (String beanName : annotateBeans) {
        /* ... and get the bean definition of each declared beans */
        Optional<MethodMetadata> metadata = getMethodMetadata(factory.getMergedBeanDefinition(beanName));
        if (metadata.isPresent()) {
            Set<Relationship> rel = detectMethodMetadata(metadata.get());
            result.addAll(rel);
        }
    }
    return result;
}
DataJpaConfig.java 文件源码 项目:spring-microservice-sample 阅读 24 收藏 0 点赞 0 评论 0
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public AuditorAware<Username> auditorAware() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    log.debug("current authentication:" + authentication);

    if (authentication == null || !authentication.isAuthenticated()) {
        return () -> Optional.<Username>empty();
    }

    return () -> Optional.of(
        Username.builder()
            .username(((UserDetails) authentication.getPrincipal()).getUsername())
            .build()
    );

}
HandlerMethodService.java 文件源码 项目:wamp2spring 阅读 26 收藏 0 点赞 0 评论 0
public HandlerMethodService(ConversionService conversionService,
        List<HandlerMethodArgumentResolver> customArgumentResolvers,
        ObjectMapper objectMapper, ApplicationContext applicationContext) {
    this.conversionService = conversionService;
    this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    this.argumentResolvers = new HandlerMethodArgumentResolverComposite();

    ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue(
            ConfigurableApplicationContext.class, applicationContext)
                    ? ((ConfigurableApplicationContext) applicationContext)
                            .getBeanFactory()
                    : null;

    this.argumentResolvers.addResolver(
            new HeaderMethodArgumentResolver(this.conversionService, beanFactory));
    this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver());
    this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver());
    this.argumentResolvers.addResolvers(customArgumentResolvers);

    this.objectMapper = objectMapper;
}
ScriptFactoryPostProcessor.java 文件源码 项目:lams 阅读 16 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
ConfigurationClassParser.java 文件源码 项目:lams 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and
 * {@link BeanFactoryAware} contracts if implemented by the given {@code bean}.
 */
private void invokeAwareMethods(Object importStrategyBean) {
    if (importStrategyBean instanceof Aware) {
        if (importStrategyBean instanceof EnvironmentAware) {
            ((EnvironmentAware) importStrategyBean).setEnvironment(this.environment);
        }
        if (importStrategyBean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) importStrategyBean).setResourceLoader(this.resourceLoader);
        }
        if (importStrategyBean instanceof BeanClassLoaderAware) {
            ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ?
                    ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() :
                    this.resourceLoader.getClassLoader());
            ((BeanClassLoaderAware) importStrategyBean).setBeanClassLoader(classLoader);
        }
        if (importStrategyBean instanceof BeanFactoryAware && this.registry instanceof BeanFactory) {
            ((BeanFactoryAware) importStrategyBean).setBeanFactory((BeanFactory) this.registry);
        }
    }
}
ConfigurationClassEnhancer.java 文件源码 项目:lams 阅读 20 收藏 0 点赞 0 评论 0
/**
 * Create a subclass proxy that intercepts calls to getObject(), delegating to the current BeanFactory
 * instead of creating a new instance. These proxies are created only when calling a FactoryBean from
 * within a Bean method, allowing for proper scoping semantics even when working against the FactoryBean
 * instance directly. If a FactoryBean instance is fetched through the container via &-dereferencing,
 * it will not be proxied. This too is aligned with the way XML configuration works.
 */
private Object enhanceFactoryBean(Class<?> fbClass, final ConfigurableBeanFactory beanFactory,
        final String beanName) throws InstantiationException, IllegalAccessException {

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(fbClass);
    enhancer.setUseFactory(false);
    enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    enhancer.setCallback(new MethodInterceptor() {
        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            if (method.getName().equals("getObject") && args.length == 0) {
                return beanFactory.getBean(beanName);
            }
            return proxy.invokeSuper(obj, args);
        }
    });
    return enhancer.create();
}
CommonAnnotationBeanPostProcessor.java 文件源码 项目:lams 阅读 26 收藏 0 点赞 0 评论 0
@Override
protected Object getResourceToInject(Object target, String requestingBeanName) {
    if (StringUtils.hasLength(this.beanName)) {
        if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
            // Local match found for explicitly specified local bean name.
            Object bean = beanFactory.getBean(this.beanName, this.lookupType);
            if (beanFactory instanceof ConfigurableBeanFactory) {
                ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName);
            }
            return bean;
        }
        else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) {
            throw new NoSuchBeanDefinitionException(this.beanName,
                    "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead.");
        }
    }
    // JNDI name lookup - may still go to a local BeanFactory.
    return getResource(this, requestingBeanName);
}
AbstractBeanFactory.java 文件源码 项目:lams 阅读 17 收藏 0 点赞 0 评论 0
@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
    String beanName = transformedBeanName(name);

    Object beanInstance = getSingleton(beanName, false);
    if (beanInstance != null) {
        return (beanInstance instanceof FactoryBean);
    }
    else if (containsSingleton(beanName)) {
        // null instance registered
        return false;
    }

    // No singleton instance found -> check bean definition.
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
    }

    return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
AbstractPrototypeBasedTargetSource.java 文件源码 项目:lams 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Subclasses should call this method to destroy an obsolete prototype instance.
 * @param target the bean instance to destroy
 */
protected void destroyPrototypeInstance(Object target) {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'");
    }
    if (getBeanFactory() instanceof ConfigurableBeanFactory) {
        ((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target);
    }
    else if (target instanceof DisposableBean) {
        try {
            ((DisposableBean) target).destroy();
        }
        catch (Throwable ex) {
            logger.error("Couldn't invoke destroy method of bean with name '" + getTargetBeanName() + "'", ex);
        }
    }
}
AbstractBeanFactoryBasedTargetSourceCreator.java 文件源码 项目:lams 阅读 19 收藏 0 点赞 0 评论 0
/**
 * Build an internal BeanFactory for resolving target beans.
 * @param containingFactory the containing BeanFactory that originally defines the beans
 * @return an independent internal BeanFactory to hold copies of some target beans
 */
protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) {
    // Set parent so that references (up container hierarchies) are correctly resolved.
    DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    internalBeanFactory.copyConfigurationFrom(containingFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }

    return internalBeanFactory;
}
PersistenceAnnotationBeanPostProcessor.java 文件源码 项目:lams 阅读 28 收藏 0 点赞 0 评论 0
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
WxBuildinMvcConfiguration.java 文件源码 项目:FastBootWeixin 阅读 21 收藏 0 点赞 0 评论 0
@Override
public void afterPropertiesSet() throws Exception {
    RequestMappingHandlerAdapter requestMappingHandlerAdapter = this.beanFactory.getBean(RequestMappingHandlerAdapter.class);
    List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
    List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>();
    if (beanFactory instanceof ConfigurableBeanFactory) {
        argumentResolvers.add(new WxArgumentResolver((ConfigurableBeanFactory) beanFactory));
    } else {
        argumentResolvers.add(new WxArgumentResolver(beanFactory.getBean(WxUserManager.class), beanFactory.getBean(WxUserProvider.class)));
    }
    returnValueHandlers.add(beanFactory.getBean(WxAsyncMessageReturnValueHandler.class));
    argumentResolvers.addAll(requestMappingHandlerAdapter.getArgumentResolvers());
    returnValueHandlers.addAll(requestMappingHandlerAdapter.getReturnValueHandlers());
    requestMappingHandlerAdapter.setArgumentResolvers(argumentResolvers);
    requestMappingHandlerAdapter.setReturnValueHandlers(returnValueHandlers);
}
DefaultMessageHandlerMethodFactory.java 文件源码 项目:spring4-understanding 阅读 19 收藏 0 点赞 0 评论 0
protected List<HandlerMethodArgumentResolver> initArgumentResolvers() {
    List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>();
    ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory ?
            (ConfigurableBeanFactory) this.beanFactory : null);

    // Annotation-based argument resolution
    resolvers.add(new HeaderMethodArgumentResolver(this.conversionService, cbf));
    resolvers.add(new HeadersMethodArgumentResolver());

    // Type-based argument resolution
    resolvers.add(new MessageMethodArgumentResolver());

    if (this.customArgumentResolvers != null) {
        resolvers.addAll(this.customArgumentResolvers);
    }
    resolvers.add(new PayloadArgumentResolver(this.messageConverter, this.validator));

    return resolvers;
}
ComponentScanAnnotationParser.java 文件源码 项目:spring 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and
 * {@link BeanFactoryAware} contracts if implemented by the given {@code filter}.
 */
private void invokeAwareMethods(TypeFilter filter) {
    if (filter instanceof Aware) {
        if (filter instanceof EnvironmentAware) {
            ((EnvironmentAware) filter).setEnvironment(this.environment);
        }
        if (filter instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) filter).setResourceLoader(this.resourceLoader);
        }
        if (filter instanceof BeanClassLoaderAware) {
            ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ?
                    ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() :
                    this.resourceLoader.getClassLoader());
            ((BeanClassLoaderAware) filter).setBeanClassLoader(classLoader);
        }
        if (filter instanceof BeanFactoryAware && this.registry instanceof BeanFactory) {
            ((BeanFactoryAware) filter).setBeanFactory((BeanFactory) this.registry);
        }
    }
}
ScriptFactoryPostProcessor.java 文件源码 项目:spring4-understanding 阅读 18 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
ConfigurationClassParser.java 文件源码 项目:spring4-understanding 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and
 * {@link BeanFactoryAware} contracts if implemented by the given {@code bean}.
 */
private void invokeAwareMethods(Object importStrategyBean) {
    if (importStrategyBean instanceof Aware) {
        if (importStrategyBean instanceof EnvironmentAware) {
            ((EnvironmentAware) importStrategyBean).setEnvironment(this.environment);
        }
        if (importStrategyBean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) importStrategyBean).setResourceLoader(this.resourceLoader);
        }
        if (importStrategyBean instanceof BeanClassLoaderAware) {
            ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ?
                    ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() :
                    this.resourceLoader.getClassLoader());
            ((BeanClassLoaderAware) importStrategyBean).setBeanClassLoader(classLoader);
        }
        if (importStrategyBean instanceof BeanFactoryAware && this.registry instanceof BeanFactory) {
            ((BeanFactoryAware) importStrategyBean).setBeanFactory((BeanFactory) this.registry);
        }
    }
}
CommonAnnotationBeanPostProcessor.java 文件源码 项目:spring4-understanding 阅读 23 收藏 0 点赞 0 评论 0
@Override
protected Object getResourceToInject(Object target, String requestingBeanName) {
    if (StringUtils.hasLength(this.beanName)) {
        if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
            // Local match found for explicitly specified local bean name.
            Object bean = beanFactory.getBean(this.beanName, this.lookupType);
            if (beanFactory instanceof ConfigurableBeanFactory) {
                ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName);
            }
            return bean;
        }
        else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) {
            throw new NoSuchBeanDefinitionException(this.beanName,
                    "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead.");
        }
    }
    // JNDI name lookup - may still go to a local BeanFactory.
    return getResource(this, requestingBeanName);
}
CommonAnnotationBeanPostProcessor.java 文件源码 项目:spring 阅读 24 收藏 0 点赞 0 评论 0
@Override
protected Object getResourceToInject(Object target, String requestingBeanName) {
    if (StringUtils.hasLength(this.beanName)) {
        if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
            // Local match found for explicitly specified local bean name.
            Object bean = beanFactory.getBean(this.beanName, this.lookupType);
            if (beanFactory instanceof ConfigurableBeanFactory) {
                ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName);
            }
            return bean;
        }
        else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) {
            throw new NoSuchBeanDefinitionException(this.beanName,
                    "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead.");
        }
    }
    // JNDI name lookup - may still go to a local BeanFactory.
    return getResource(this, requestingBeanName);
}
AbstractBeanFactory.java 文件源码 项目:spring4-understanding 阅读 25 收藏 0 点赞 0 评论 0
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
    Assert.notNull(otherFactory, "BeanFactory must not be null");
    setBeanClassLoader(otherFactory.getBeanClassLoader());
    setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
    setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
    if (otherFactory instanceof AbstractBeanFactory) {
        AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
        this.customEditors.putAll(otherAbstractFactory.customEditors);
        this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
        this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
        this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
                otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
        this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
                otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
        this.scopes.putAll(otherAbstractFactory.scopes);
        this.securityContextProvider = otherAbstractFactory.securityContextProvider;
    }
    else {
        setTypeConverter(otherFactory.getTypeConverter());
    }
}
AbstractBeanFactoryBasedTargetSourceCreator.java 文件源码 项目:spring 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Build an internal BeanFactory for resolving target beans.
 * @param containingFactory the containing BeanFactory that originally defines the beans
 * @return an independent internal BeanFactory to hold copies of some target beans
 */
protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) {
    // Set parent so that references (up container hierarchies) are correctly resolved.
    DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    internalBeanFactory.copyConfigurationFrom(containingFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }

    return internalBeanFactory;
}
CallbacksSecurityTests.java 文件源码 项目:spring4-understanding 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void testInitSecurityAwarePrototypeBean() {
    final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    BeanDefinitionBuilder bdb = BeanDefinitionBuilder
            .genericBeanDefinition(NonPrivilegedBean.class).setScope(
                    ConfigurableBeanFactory.SCOPE_PROTOTYPE)
            .setInitMethodName("init").setDestroyMethodName("destroy")
            .addConstructorArgValue("user1");
    lbf.registerBeanDefinition("test", bdb.getBeanDefinition());
    final Subject subject = new Subject();
    subject.getPrincipals().add(new TestPrincipal("user1"));

    NonPrivilegedBean bean = Subject.doAsPrivileged(
            subject, new PrivilegedAction<NonPrivilegedBean>() {
                @Override
                public NonPrivilegedBean run() {
                    return lbf.getBean("test", NonPrivilegedBean.class);
                }
            }, null);
    assertNotNull(bean);
}
AbstractBeanFactoryTests.java 文件源码 项目:spring4-understanding 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void aliasing() {
    BeanFactory bf = getBeanFactory();
    if (!(bf instanceof ConfigurableBeanFactory)) {
        return;
    }
    ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;

    String alias = "rods alias";
    try {
        cbf.getBean(alias);
        fail("Shouldn't permit factory get on normal bean");
    }
    catch (NoSuchBeanDefinitionException ex) {
        // Ok
        assertTrue(alias.equals(ex.getBeanName()));
    }

    // Create alias
    cbf.registerAlias("rod", alias);
    Object rod = getBeanFactory().getBean("rod");
    Object aliasRod = getBeanFactory().getBean(alias);
    assertTrue(rod == aliasRod);
}
ScriptFactoryPostProcessor.java 文件源码 项目:my-spring-cache-redis 阅读 20 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
SpringNettyConfiguration.java 文件源码 项目:spring-boot-netty 阅读 20 收藏 0 点赞 0 评论 0
private <T> Supplier<T> createHandlerBeanSupplier(final T h, final Class<? extends T> handlerClass,
                                                  final String beanName) {

    final ChannelHandler.Sharable sharable = findAnnotation(handlerClass, ChannelHandler.Sharable.class);
    if (sharable == null) {
        final Scope scope = findAnnotation(handlerClass, Scope.class);
        if ((scope == null) || !ConfigurableBeanFactory.SCOPE_PROTOTYPE.equals(scope.value())) {
            throw new IllegalStateException("Non-sharable handler should be presented by a " +
                    "prototype bean");
        }
    }

    return (sharable == null) ?
            () -> beanFactory.getBean(beanName, handlerClass) :
            () -> h;
}
ConfigurationClassEnhancer.java 文件源码 项目:my-spring-cache-redis 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Create a subclass proxy that intercepts calls to getObject(), delegating to the current BeanFactory
 * instead of creating a new instance. These proxies are created only when calling a FactoryBean from
 * within a Bean method, allowing for proper scoping semantics even when working against the FactoryBean
 * instance directly. If a FactoryBean instance is fetched through the container via &-dereferencing,
 * it will not be proxied. This too is aligned with the way XML configuration works.
 */
private Object enhanceFactoryBean(Class<?> fbClass, final ConfigurableBeanFactory beanFactory,
        final String beanName) throws InstantiationException, IllegalAccessException {

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(fbClass);
    enhancer.setUseFactory(false);
    enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    enhancer.setCallback(new MethodInterceptor() {
        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            if (method.getName().equals("getObject") && args.length == 0) {
                return beanFactory.getBean(beanName);
            }
            return proxy.invokeSuper(obj, args);
        }
    });
    return enhancer.create();
}
ScriptFactoryPostProcessor.java 文件源码 项目:spring 阅读 20 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
CommonAnnotationBeanPostProcessor.java 文件源码 项目:my-spring-cache-redis 阅读 28 收藏 0 点赞 0 评论 0
@Override
protected Object getResourceToInject(Object target, String requestingBeanName) {
    if (StringUtils.hasLength(this.beanName)) {
        if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
            // Local match found for explicitly specified local bean name.
            Object bean = beanFactory.getBean(this.beanName, this.lookupType);
            if (beanFactory instanceof ConfigurableBeanFactory) {
                ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName);
            }
            return bean;
        }
        else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) {
            throw new NoSuchBeanDefinitionException(this.beanName,
                    "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead.");
        }
    }
    // JNDI name lookup - may still go to a local BeanFactory.
    return getResource(this, requestingBeanName);
}
ConfigBeanPostProcessor.java 文件源码 项目:configx 阅读 20 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}
ConfigPropertyResolver.java 文件源码 项目:configx 阅读 29 收藏 0 点赞 0 评论 0
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}


问题


面经


文章

微信
公众号

扫码关注公众号