Java Code Examples for org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerSingleton()

The following examples show how to use org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerSingleton() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NacosPropertySourcePostProcessorTest.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
private AnnotationConfigApplicationContext createContext(String dataId,
		String groupId, String content) throws NacosException {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

	ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();

	configService.publishConfig(dataId, groupId, content);

	beanFactory.registerSingleton(CONFIG_SERVICE_BEAN_NAME, configService);

	context.register(AnnotationNacosInjectedBeanPostProcessor.class,
			NacosPropertySourcePostProcessor.class, ConfigServiceBeanBuilder.class,
			AnnotationNacosPropertySourceBuilder.class, TestConfiguration.class,
			TestApplicationHolder.class);
	return context;
}
 
Example 2
Source File: DubboAutoConfiguration.java    From spring-boot-starter-dubbo with Apache License 2.0 6 votes vote down vote up
private void registerProvider(ProviderConfig provider, ConfigurableListableBeanFactory beanFactory) {
	if (provider != null) {
		String beanName = provider.getId();
		if (StringUtils.isEmpty(beanName)) {
			beanName = "providerConfig";
		}
		String filter = provider.getFilter();
		if (StringUtils.isEmpty(filter)) {
			filter = "regerProviderFilter";
		} else {
			filter = filter.trim() + ",regerProviderFilter";
		}
		logger.debug("添加consumerFilter后的Filter, {}", filter);
		provider.setFilter(filter);
		beanFactory.registerSingleton(beanName, provider);
	} else {
		logger.debug("dubbo 没有配置默认的生成者参数");
	}
}
 
Example 3
Source File: DubboAutoConfiguration.java    From spring-boot-starter-dubbo with Apache License 2.0 6 votes vote down vote up
private void registerConsumer(ConsumerConfig consumer, ConfigurableListableBeanFactory beanFactory) {
	if (consumer != null) {
		String beanName = consumer.getId();
		if (StringUtils.isEmpty(beanName)) {
			beanName = "consumerConfig";
		}
		String filter = consumer.getFilter();
		if (StringUtils.isEmpty(filter)) {
			filter = "regerConsumerFilter";
		} else {
			filter = filter.trim() + ",regerConsumerFilter";
		}
		logger.debug("添加consumerFilter后的Filter, {}", filter);
		consumer.setFilter(filter);
		beanFactory.registerSingleton(beanName, consumer);
	} else {
		logger.debug("dubbo 没有配置默认的消费者参数");
	}
}
 
Example 4
Source File: RatelContextApplier.java    From Ratel with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    final RegistryStrategiesProvider registryBeanProvider = registryBeanProviderFactory.create(beanFactory);
    if (registryBeanProvider == null) {
        //Ratel is disabled, stop further processing
        return;
    }

    final ServiceRegisterPostProcessor serviceRegisterPostProcessor = serviceRegisterPostProcessorFactory.create(beanFactory,
            registryBeanProvider.getRegisterStrategy());
    beanFactory.registerSingleton(serviceRegisterPostProcessor.getClass().getName(), serviceRegisterPostProcessor);

    RatelClientProducer ratelClientProducer = new RatelClientProducer(registryBeanProvider.getFetchStrategy(),
            registryBeanProvider.getClientProxyGenerator());
    final RemoteAutowireCandidateResolver autowireCandidateResolver = new RemoteAutowireCandidateResolver(
            ratelClientProducer);
    ((DefaultListableBeanFactory) beanFactory).setAutowireCandidateResolver(autowireCandidateResolver);

    ((DefaultListableBeanFactory) beanFactory).setAutowireCandidateResolver(autowireCandidateResolver);

}
 
Example 5
Source File: MapperScannerWithSharding.java    From tsharding with MIT License 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    this.dataSourceLookup = beanFactory.getBean(DataSourceLookup.class);

    try {
        this.initSqlSessionFactories(beanFactory);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    ClassPathScanHandler scanner = new ClassPathScanHandler();
    Set<Class<?>> mapperClasses = new HashSet<>();
    for (String mapperPackage : this.mapperPacakages) {
        Set<Class<?>> classes = scanner.getPackageAllClasses(mapperPackage.trim(), false);
        mapperClasses.addAll(classes);
    }
    for (Class<?> clazz : mapperClasses) {
        if (isMapper(clazz)) {
            Object mapper = this.newMapper(clazz);
            beanFactory.registerSingleton(Character.toLowerCase(clazz.getSimpleName().charAt(0))
                    + clazz.getSimpleName().substring(1), mapper);
        }
    }

}
 
Example 6
Source File: SpringBeanLocatorTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testWait() throws InterruptedException {
    ConfigurableApplicationContext context = new GenericApplicationContext();
    ConfigurableListableBeanFactory factory = context.getBeanFactory();
    Object bean = new Object();
    factory.registerSingleton("test", bean);
    context.refresh();
    Locator get1 = new Locator(SpringBeanLocator.getInstance());
    Locator get2 = new Locator(SpringBeanLocator.getInstance());
    get1.start();
    get2.start();

    // Increase the chances that the other threads will have run
    Thread.yield();

    SpringBeanLocator.setApplicationContext(context);
    get1.join(10000);
    get2.join(10000);
    // Cross thread assertions
    Assert.assertTrue(get1.good);
    Assert.assertTrue(get2.good);
}
 
Example 7
Source File: AbstractApplicationContext.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */
protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster =
				beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
		if (logger.isDebugEnabled()) {
			logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	else {
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isDebugEnabled()) {
			logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
					APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
					"': using default [" + this.applicationEventMulticaster + "]");
		}
	}
}
 
Example 8
Source File: DubboAutoConfiguration.java    From spring-boot-starter-dubbo with Apache License 2.0 6 votes vote down vote up
private void registerProtocols(List<ProtocolConfig> protocols, ConfigurableListableBeanFactory beanFactory) {
	if (protocols == null || protocols.isEmpty()) {
		logger.info("dubbo 没有配置协议,将使用默认协议");
		return;
	}
	for (int index = 0; index < protocols.size(); index++) {
		ProtocolConfig protocol = protocols.get(index);
		String beanName = protocol.getId();
		if (StringUtils.isEmpty(beanName)) {
			beanName = "protocolConfig" + index;
		}
		if (protocol.getPort() == null || protocol.getPort() == 0) {
			protocol.setPort(SocketUtils.findAvailableTcpPort(53600, 53688));
		}
		beanFactory.registerSingleton(beanName, protocol);
		logger.debug("注册协议信息{}完毕", beanName);
	}
}
 
Example 9
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize the LifecycleProcessor.
 * Uses DefaultLifecycleProcessor if none defined in the context.
 * @see org.springframework.context.support.DefaultLifecycleProcessor
 */
protected void initLifecycleProcessor() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
		this.lifecycleProcessor =
				beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
		}
	}
	else {
		DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
		defaultProcessor.setBeanFactory(beanFactory);
		this.lifecycleProcessor = defaultProcessor;
		beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
					"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
		}
	}
}
 
Example 10
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */
protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	// 如有有自己注册class Name 是 applicationEventMulticaster,使用自定义广播器
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster =
				beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	else {
		// 没有自定义,使用默认的事件广播器
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
					"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
		}
	}
}
 
Example 11
Source File: DubboAutoConfiguration.java    From spring-boot-starter-dubbo with Apache License 2.0 5 votes vote down vote up
private void registerReferences(List<ReferenceConfig<?>> references, ConfigurableListableBeanFactory beanFactory) {
	if (references == null || references.isEmpty()) {
		return;
	}
	for (int index = 0; index < references.size(); index++) {
		ReferenceConfig<?> referenceConfig = references.get(index);
		String beanName = referenceConfig.getId();
		if (StringUtils.isEmpty(beanName)) {
			beanName = "referenceConfig" + index;
		}
		beanFactory.registerSingleton(beanName, referenceConfig);
		beanFactory.registerSingleton(beanName, referenceConfig.get());
		logger.debug("注册服务调用信息{} 完毕", beanName);
	}
}
 
Example 12
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomBatchingStrategy() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
	producerProperties.getExtension().setBatchingEnabled(true);
	producerProperties.getExtension().setBatchingStrategyBeanName("testCustomBatchingStrategy");
	producerProperties.setRequiredGroups("default");

	ConfigurableListableBeanFactory beanFactory = binder.getApplicationContext().getBeanFactory();
	beanFactory.registerSingleton("testCustomBatchingStrategy", new TestBatchingStrategy());

	DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties));
	output.setBeanName("batchingProducer");
	Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0", output, producerProperties);

	Log logger = spy(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.logger", Log.class));
	new DirectFieldAccessor(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor"))
			.setPropertyValue("logger", logger);
	when(logger.isTraceEnabled()).thenReturn(true);

	assertThat(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.level"))
			.isEqualTo(Deflater.BEST_SPEED);

	output.send(new GenericMessage<>("0".getBytes()));
	output.send(new GenericMessage<>("1".getBytes()));
	output.send(new GenericMessage<>("2".getBytes()));
	output.send(new GenericMessage<>("3".getBytes()));
	output.send(new GenericMessage<>("4".getBytes()));

	Object out = spyOn("batching.0.default").receive(false);
	assertThat(out).isInstanceOf(byte[].class);
	assertThat(new String((byte[]) out)).isEqualTo("0\u0000\n1\u0000\n2\u0000\n3\u0000\n4\u0000\n");

	producerBinding.unbind();
}
 
Example 13
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadUserDeclarationsFatal() throws Exception {
	RabbitTestBinder binder = getBinder();
	ConfigurableApplicationContext context = binder.getApplicationContext();
	ConfigurableListableBeanFactory bf = context.getBeanFactory();
	bf.registerSingleton("testBadUserDeclarationsFatal",
			new Queue("testBadUserDeclarationsFatal", false));
	bf.registerSingleton("binder", binder);
	RabbitExchangeQueueProvisioner provisioner = TestUtils.getPropertyValue(binder,
			"binder.provisioningProvider", RabbitExchangeQueueProvisioner.class);
	bf.initializeBean(provisioner, "provisioner");
	bf.registerSingleton("provisioner", provisioner);
	context.addApplicationListener(provisioner);
	RabbitAdmin admin = new RabbitAdmin(rabbitAvailableRule.getResource());
	admin.declareQueue(new Queue("testBadUserDeclarationsFatal"));
	// reset the connection and configure the "user" admin to auto declare queues...
	rabbitAvailableRule.getResource().resetConnection();
	bf.initializeBean(admin, "rabbitAdmin");
	bf.registerSingleton("rabbitAdmin", admin);
	admin.afterPropertiesSet();
	// the mis-configured queue should be fatal
	Binding<?> binding = null;
	try {
		binding = binder.bindConsumer("input", "baddecls",
				this.createBindableChannel("input", new BindingProperties()),
				createConsumerProperties());
		fail("Expected exception");
	}
	catch (BinderException e) {
		assertThat(e.getCause()).isInstanceOf(AmqpIOException.class);
	}
	finally {
		admin.deleteQueue("testBadUserDeclarationsFatal");
		if (binding != null) {
			binding.unbind();
		}
	}
}
 
Example 14
Source File: DubboAutoConfiguration.java    From spring-boot-starter-dubbo with Apache License 2.0 5 votes vote down vote up
private void registerModule(ModuleConfig module, ConfigurableListableBeanFactory beanFactory) {
	if (module != null) {
		String beanName = module.getId();
		if (StringUtils.isEmpty(beanName)) {
			beanName = "moduleConfig";
		}
		beanFactory.registerSingleton(beanName, module);
	} else {
		logger.debug("dubbo 没有配置模块信息");
	}
}
 
Example 15
Source File: KubernetesReconcilerProcessor.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
    throws BeansException {
  SharedInformerFactory sharedInformerFactory = beanFactory.getBean(SharedInformerFactory.class);
  String[] names = beanFactory.getBeanNamesForType(Reconciler.class);
  for (String name : names) {
    Reconciler reconciler = (Reconciler) beanFactory.getBean(name);
    KubernetesReconciler kubernetesReconciler =
        reconciler.getClass().getAnnotation(KubernetesReconciler.class);
    String reconcilerName = kubernetesReconciler.value();
    Controller controller = buildController(sharedInformerFactory, reconciler);
    beanFactory.registerSingleton(reconcilerName, controller);
  }
}
 
Example 16
Source File: HttpScenarioGenerator.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    try {
        Assert.notNull(swaggerResource,
                "Missing either swagger api system property setting or explicit swagger api resource for scenario auto generation");

        Swagger swagger = new SwaggerParser().parse(FileUtils.readToString(swaggerResource));

        for (Map.Entry<String, Path> path : swagger.getPaths().entrySet()) {
            for (Map.Entry<io.swagger.models.HttpMethod, Operation> operation : path.getValue().getOperationMap().entrySet()) {

                if (beanFactory instanceof BeanDefinitionRegistry) {
                    log.info("Register auto generated scenario as bean definition: " + operation.getValue().getOperationId());
                    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(HttpOperationScenario.class)
                            .addConstructorArgValue((contextPath + (swagger.getBasePath() != null ? swagger.getBasePath() : "")) + path.getKey())
                            .addConstructorArgValue(HttpMethod.valueOf(operation.getKey().name()))
                            .addConstructorArgValue(operation.getValue())
                            .addConstructorArgValue(swagger.getDefinitions());

                    if (beanFactory.containsBeanDefinition("inboundJsonDataDictionary")) {
                        beanDefinitionBuilder.addPropertyReference("inboundDataDictionary", "inboundJsonDataDictionary");
                    }

                    if (beanFactory.containsBeanDefinition("outboundJsonDataDictionary")) {
                        beanDefinitionBuilder.addPropertyReference("outboundDataDictionary", "outboundJsonDataDictionary");
                    }

                    ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(operation.getValue().getOperationId(), beanDefinitionBuilder.getBeanDefinition());
                } else {
                    log.info("Register auto generated scenario as singleton: " + operation.getValue().getOperationId());
                    beanFactory.registerSingleton(operation.getValue().getOperationId(), createScenario((contextPath + (swagger.getBasePath() != null ? swagger.getBasePath() : "")) + path.getKey(), HttpMethod.valueOf(operation.getKey().name()), operation.getValue(), swagger.getDefinitions()));
                }
            }
        }
    } catch (IOException e) {
        throw new SimulatorException("Failed to read swagger api resource", e);
    }
}
 
Example 17
Source File: CloudPropertiesFactoryBean.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	ConfigurableListableBeanFactory listableBeanFactory = (ConfigurableListableBeanFactory) beanFactory;
	
	if (cloud == null) {
		if(listableBeanFactory.getBeansOfType(CloudFactory.class).isEmpty()) {
			listableBeanFactory.registerSingleton(CLOUD_FACTORY_BEAN_NAME , new CloudFactory());
		}
		CloudFactory cloudFactory = listableBeanFactory.getBeansOfType(CloudFactory.class).values().iterator().next();
		cloud = cloudFactory.getCloud();
	}
}
 
Example 18
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	// 这一步中,给 beanFactory 注册了个 beanPostProcessor,后处理器的类型是 ApplicationContextAwareProcessor
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 19
Source File: AbstractApplicationContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 20
Source File: ArchivaDavResourceFactoryTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testRequestMetadataRepoIsLegacy()
    throws Exception
{
    ManagedRepositoryContent legacyRepo = createManagedRepositoryContent( LEGACY_REPO );
    ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    RepositoryContentProvider provider = createRepositoryContentProvider(legacyRepo );
    beanFactory.registerSingleton("repositoryContentProvider#legacy", provider);
    RepositoryContentFactory repoContentFactory = applicationContext.getBean( "repositoryContentFactory#default", RepositoryContentFactory.class );
    repoContentFactory.getRepositoryContentProviders().add(provider);
    defaultManagedRepositoryAdmin.addManagedRepository(
        createManagedRepository( LEGACY_REPO, getProjectBase().resolve( "target/test-classes/" + LEGACY_REPO ).toString(),
            "legacy" ), false, null );

    DavResourceLocator locator =
        new ArchivaDavResourceLocator( "", "/repository/" + LEGACY_REPO + "/eclipse/maven-metadata.xml",
                                       LEGACY_REPO, new ArchivaDavLocatorFactory() );


    try
    {
        archivaConfigurationControl.reset();

        expect( archivaConfiguration.getConfiguration() ).andReturn( config ).times( 2 );

        expect( repoFactory.getManagedRepositoryContent( LEGACY_REPO ) ).andReturn( legacyRepo );

        expect( request.getMethod() ).andReturn( "GET" ).times( 3 );

        expect( request.getRemoteAddr() ).andReturn( "http://localhost:8080" ).times( 3 );

        expect( request.getDavSession() ).andReturn( new ArchivaDavSession() ).times( 2 );

        expect( request.getContextPath() ).andReturn( "" ).times( 2 );

        archivaConfigurationControl.replay();
        repoContentFactoryControl.replay();
        requestControl.replay();

        resourceFactory.createResource( locator, request, response );

        archivaConfigurationControl.verify();
        repoContentFactoryControl.verify();
        requestControl.verify();

        fail( "A 404 error should have been thrown!" );
    }
    catch ( DavException e )
    {
        assertEquals( 404, e.getErrorCode() );
    }
}