Java Code Examples for org.springframework.context.ConfigurableApplicationContext#getBeanFactory()

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#getBeanFactory() . These examples are extracted from open source projects. 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
@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 2
@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 3
Source Project: mPaaS   File: SwaggerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 动态产生Docket分组信息
 *
 * @return
 */
@Autowired
public void dynamicConfiguration() {
    ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    String systemName = "Microservice PaaS";
    ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder()
            .description("mPaas前端后端对应接口")
            .version("1.0.1")
            .license("Code Farmer Framework(iByte) Org.");

    Map<String, ModuleMappingInfo> moduleInfo = mappingHelper.getMappingInfos();
    for (Map.Entry<String, ModuleMappingInfo> entry : moduleInfo.entrySet()) {
        beanFactory.registerSingleton(entry.getKey(), new Docket(DocumentationType.SWAGGER_2)
                .groupName(entry.getKey())
                .apiInfo(apiInfoBuilder.title(systemName + NamingConstant.DOT + entry.getKey()).build())
                .select()
                .apis(genSubPackage(entry.getKey()))
                .paths(Predicates.or(PathSelectors.ant(NamingConstant.PATH_PREFIX_DATA + "/**"),
                        PathSelectors.ant(NamingConstant.PATH_PREFIX_API + "/**")))
                .build());
    }
}
 
Example 4
@SuppressWarnings("unchecked")
PartitionAwareFunctionWrapper(FunctionInvocationWrapper function, ConfigurableApplicationContext context, ProducerProperties producerProperties) {
	this.function = function;
	if (producerProperties != null && producerProperties.isPartitioned()) {
		StandardEvaluationContext evaluationContext = ExpressionUtils.createStandardEvaluationContext(context.getBeanFactory());
		PartitionHandler partitionHandler = new PartitionHandler(evaluationContext, producerProperties, context.getBeanFactory());

		this.outputMessageEnricher = outputMessage -> {
			int partitionId = partitionHandler.determinePartition(outputMessage);
			return MessageBuilder
				.fromMessage(outputMessage)
				.setHeader(BinderHeaders.PARTITION_HEADER, partitionId).build();
		};
	}
	else {
		this.outputMessageEnricher = null;
	}
}
 
Example 5
Source Project: spring-zk-test   File: RegisterBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 动态注册bean
 * 
 * @author JohnGao
 */
public <T> void register(String beanName, Class<T> classType,
		Map<String, String> values) {
	ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) aContext;
	DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext
			.getBeanFactory();
	if (defaultListableBeanFactory.isBeanNameInUse(beanName)) {
		defaultListableBeanFactory.removeBeanDefinition(beanName);
		logger.info("beanName-->" + beanName + "成功删除");
	}
	BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
			.genericBeanDefinition(classType);
	for (String key : values.keySet())
		beanDefinitionBuilder.addPropertyValue(key, values.get(key));
	defaultListableBeanFactory.registerBeanDefinition(beanName,
			beanDefinitionBuilder.getRawBeanDefinition());
	logger.info("beanName-->" + beanName + "成功注册");
}
 
Example 6
Source Project: shark   File: RegisterDataSource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 注册bean
 * 
 * @author gaoxianglong
 * 
 * @param nodePathValue
 *            value 从配置中心订阅的配置信息
 * 
 * @param resourceType
 *            注册中心类型
 * 
 * @return void
 */
public static void register(String value, String resourceType) {
	if (null == aContext || null == value)
		return;
	ConfigurableApplicationContext cfgContext = (ConfigurableApplicationContext) aContext;
	DefaultListableBeanFactory beanfactory = (DefaultListableBeanFactory) cfgContext.getBeanFactory();
	/*
	 * 将配置中心获取的配置信息与当前上下文中的ioc容器进行合并,不需要手动移除之前的bean,
	 * 调用loadBeanDefinitions()方法时会进行自动移除
	 */
	new XmlBeanDefinitionReader(beanfactory).loadBeanDefinitions(new ByteArrayResource(value.getBytes()));
	final String defaultBeanName = "jdbcTemplate";
	String[] beanNames = beanfactory.getBeanDefinitionNames();
	for (String beanName : beanNames) {
		/* 替换上下文中缺省beanName为jdbcTemplate的JdbcTemplate的引用 */
		if (defaultBeanName.equals(beanName)) {
			GetJdbcTemplate.setJdbcTemplate((JdbcTemplate) beanfactory.getBean(defaultBeanName));
		} else {
			/* 实例化所有所有未实例化的bean */
			beanfactory.getBean(beanName);
		}
	}
}
 
Example 7
/**
 * Load the application context using a single classloader
 * @param ac The spring application context
 * @param config a list of configurations represented as List of resources
 * @param loader the classloader to use
 */
public void loadComponent(ConfigurableApplicationContext ac,
		List<Resource> config, ClassLoader loader) {
	ClassLoader current = Thread.currentThread().getContextClassLoader();

	Thread.currentThread().setContextClassLoader(loader);

	try {

		// make a reader
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
				(BeanDefinitionRegistry) ac.getBeanFactory());

		// In Spring 2, classes aren't loaded during bean parsing unless
		// this
		// classloader property is set.
		reader.setBeanClassLoader(loader);

		reader.loadBeanDefinitions(config.toArray(new Resource[0]));
	} catch (Throwable t) {
		log.warn("loadComponentPackage: exception loading: " + config
				+ " : " + t, t);
	} finally {
		// restore the context loader
		Thread.currentThread().setContextClassLoader(current);
	}

}
 
Example 8
private void setUpRequestContextIfNecessary(TestContext testContext) {
	if (notAnnotatedWithWebAppConfiguration(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
		return;
	}

	ApplicationContext context = testContext.getApplicationContext();

	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext servletContext = wac.getServletContext();
		Assert.state(servletContext instanceof MockServletContext, String.format(
			"The WebApplicationContext for test context %s must be configured with a MockServletContext.",
			testContext));

		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
				"Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
				testContext));
		}

		MockServletContext mockServletContext = (MockServletContext) servletContext;
		MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
		request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

		RequestContextHolder.setRequestAttributes(servletWebRequest);
		testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
		testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

		if (wac instanceof ConfigurableApplicationContext) {
			@SuppressWarnings("resource")
			ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
			ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
			bf.registerResolvableDependency(MockHttpServletResponse.class, response);
			bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
		}
	}
}
 
Example 9
private void setUpRequestContextIfNecessary(TestContext testContext) {
	if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
		return;
	}

	ApplicationContext context = testContext.getApplicationContext();

	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext servletContext = wac.getServletContext();
		Assert.state(servletContext instanceof MockServletContext, () -> String.format(
					"The WebApplicationContext for test context %s must be configured with a MockServletContext.",
					testContext));

		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
					"Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
					testContext));
		}

		MockServletContext mockServletContext = (MockServletContext) servletContext;
		MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
		request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

		RequestContextHolder.setRequestAttributes(servletWebRequest);
		testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
		testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

		if (wac instanceof ConfigurableApplicationContext) {
			@SuppressWarnings("resource")
			ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
			ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
			bf.registerResolvableDependency(MockHttpServletResponse.class, response);
			bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
		}
	}
}
 
Example 10
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();

    if (beanFactory instanceof BeanDefinitionRegistry) {
        registerWebTestClient((BeanDefinitionRegistry) beanFactory);
    }
}
 
Example 11
Source Project: ICERest   File: SpringBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 注册bean
 *
 * @param clazz
 */
public static void register(Class clazz) {
    ConfigurableApplicationContext context = getContext();
    if (context != null) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
        String beanName = Stringer.firstLowerCase(clazz.getSimpleName());
        beanFactory.registerBeanDefinition(beanName, BeanDefinitionBuilder.rootBeanDefinition(clazz).getBeanDefinition());
    }
}
 
Example 12
@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 13
/**
 * Create a new ApplicationContextAwareProcessor for the given context.
 */
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
	this.applicationContext = applicationContext;
	this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
 
Example 14
Source Project: lams   File: LiveBeansView.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Actually generate a JSON snapshot of the beans in the given ApplicationContexts.
 * <p>This implementation doesn't use any JSON parsing libraries in order to avoid
 * third-party library dependencies. It produces an array of context description
 * objects, each containing a context and parent attribute as well as a beans
 * attribute with nested bean description objects. Each bean object contains a
 * bean, scope, type and resource attribute, as well as a dependencies attribute
 * with a nested array of bean names that the present bean depends on.
 * @param contexts the set of ApplicationContexts
 * @return the JSON document
 */
protected String generateJson(Set<ConfigurableApplicationContext> contexts) {
	StringBuilder result = new StringBuilder("[\n");
	for (Iterator<ConfigurableApplicationContext> it = contexts.iterator(); it.hasNext();) {
		ConfigurableApplicationContext context = it.next();
		result.append("{\n\"context\": \"").append(context.getId()).append("\",\n");
		if (context.getParent() != null) {
			result.append("\"parent\": \"").append(context.getParent().getId()).append("\",\n");
		}
		else {
			result.append("\"parent\": null,\n");
		}
		result.append("\"beans\": [\n");
		ConfigurableListableBeanFactory bf = context.getBeanFactory();
		String[] beanNames = bf.getBeanDefinitionNames();
		boolean elementAppended = false;
		for (String beanName : beanNames) {
			BeanDefinition bd = bf.getBeanDefinition(beanName);
			if (isBeanEligible(beanName, bd, bf)) {
				if (elementAppended) {
					result.append(",\n");
				}
				result.append("{\n\"bean\": \"").append(beanName).append("\",\n");
				result.append("\"aliases\": ");
				appendArray(result, bf.getAliases(beanName));
				result.append(",\n");
				String scope = bd.getScope();
				if (!StringUtils.hasText(scope)) {
					scope = BeanDefinition.SCOPE_SINGLETON;
				}
				result.append("\"scope\": \"").append(scope).append("\",\n");
				Class<?> beanType = bf.getType(beanName);
				if (beanType != null) {
					result.append("\"type\": \"").append(beanType.getName()).append("\",\n");
				}
				else {
					result.append("\"type\": null,\n");
				}
				result.append("\"resource\": \"").append(getEscapedResourceDescription(bd)).append("\",\n");
				result.append("\"dependencies\": ");
				appendArray(result, bf.getDependenciesForBean(beanName));
				result.append("\n}");
				elementAppended = true;
			}
		}
		result.append("]\n");
		result.append("}");
		if (it.hasNext()) {
			result.append(",\n");
		}
	}
	result.append("]");
	return result.toString();
}
 
Example 15
Source Project: java-technology-stack   File: LiveBeansView.java    License: MIT License 4 votes vote down vote up
/**
 * Actually generate a JSON snapshot of the beans in the given ApplicationContexts.
 * <p>This implementation doesn't use any JSON parsing libraries in order to avoid
 * third-party library dependencies. It produces an array of context description
 * objects, each containing a context and parent attribute as well as a beans
 * attribute with nested bean description objects. Each bean object contains a
 * bean, scope, type and resource attribute, as well as a dependencies attribute
 * with a nested array of bean names that the present bean depends on.
 * @param contexts the set of ApplicationContexts
 * @return the JSON document
 */
protected String generateJson(Set<ConfigurableApplicationContext> contexts) {
	StringBuilder result = new StringBuilder("[\n");
	for (Iterator<ConfigurableApplicationContext> it = contexts.iterator(); it.hasNext();) {
		ConfigurableApplicationContext context = it.next();
		result.append("{\n\"context\": \"").append(context.getId()).append("\",\n");
		if (context.getParent() != null) {
			result.append("\"parent\": \"").append(context.getParent().getId()).append("\",\n");
		}
		else {
			result.append("\"parent\": null,\n");
		}
		result.append("\"beans\": [\n");
		ConfigurableListableBeanFactory bf = context.getBeanFactory();
		String[] beanNames = bf.getBeanDefinitionNames();
		boolean elementAppended = false;
		for (String beanName : beanNames) {
			BeanDefinition bd = bf.getBeanDefinition(beanName);
			if (isBeanEligible(beanName, bd, bf)) {
				if (elementAppended) {
					result.append(",\n");
				}
				result.append("{\n\"bean\": \"").append(beanName).append("\",\n");
				result.append("\"aliases\": ");
				appendArray(result, bf.getAliases(beanName));
				result.append(",\n");
				String scope = bd.getScope();
				if (!StringUtils.hasText(scope)) {
					scope = BeanDefinition.SCOPE_SINGLETON;
				}
				result.append("\"scope\": \"").append(scope).append("\",\n");
				Class<?> beanType = bf.getType(beanName);
				if (beanType != null) {
					result.append("\"type\": \"").append(beanType.getName()).append("\",\n");
				}
				else {
					result.append("\"type\": null,\n");
				}
				result.append("\"resource\": \"").append(getEscapedResourceDescription(bd)).append("\",\n");
				result.append("\"dependencies\": ");
				appendArray(result, bf.getDependenciesForBean(beanName));
				result.append("\n}");
				elementAppended = true;
			}
		}
		result.append("]\n");
		result.append("}");
		if (it.hasNext()) {
			result.append(",\n");
		}
	}
	result.append("]");
	return result.toString();
}
 
Example 16
/**
 * Create a new ApplicationContextAwareProcessor for the given context.
 */
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
	this.applicationContext = applicationContext;
	this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
 
Example 17
private static List<HandlerMethodArgumentResolver> initResolvers(ArgumentResolverConfigurer customResolvers,
		ReactiveAdapterRegistry reactiveRegistry, ConfigurableApplicationContext context,
		boolean supportDataBinding, List<HttpMessageReader<?>> readers) {

	ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
	boolean requestMappingMethod = !readers.isEmpty() && supportDataBinding;

	// Annotation-based...
	List<HandlerMethodArgumentResolver> result = new ArrayList<>();
	result.add(new RequestParamMethodArgumentResolver(beanFactory, reactiveRegistry, false));
	result.add(new RequestParamMapMethodArgumentResolver(reactiveRegistry));
	result.add(new PathVariableMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new PathVariableMapMethodArgumentResolver(reactiveRegistry));
	result.add(new MatrixVariableMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new MatrixVariableMapMethodArgumentResolver(reactiveRegistry));
	if (!readers.isEmpty()) {
		result.add(new RequestBodyArgumentResolver(readers, reactiveRegistry));
		result.add(new RequestPartMethodArgumentResolver(readers, reactiveRegistry));
	}
	if (supportDataBinding) {
		result.add(new ModelAttributeMethodArgumentResolver(reactiveRegistry, false));
	}
	result.add(new RequestHeaderMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new RequestHeaderMapMethodArgumentResolver(reactiveRegistry));
	result.add(new CookieValueMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new ExpressionValueMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new SessionAttributeMethodArgumentResolver(beanFactory, reactiveRegistry));
	result.add(new RequestAttributeMethodArgumentResolver(beanFactory, reactiveRegistry));

	// Type-based...
	if (!readers.isEmpty()) {
		result.add(new HttpEntityArgumentResolver(readers, reactiveRegistry));
	}
	result.add(new ModelArgumentResolver(reactiveRegistry));
	if (supportDataBinding) {
		result.add(new ErrorsMethodArgumentResolver(reactiveRegistry));
	}
	result.add(new ServerWebExchangeArgumentResolver(reactiveRegistry));
	result.add(new PrincipalArgumentResolver(reactiveRegistry));
	if (requestMappingMethod) {
		result.add(new SessionStatusMethodArgumentResolver());
	}
	result.add(new WebSessionArgumentResolver(reactiveRegistry));

	// Custom...
	result.addAll(customResolvers.getCustomResolvers());

	// Catch-all...
	result.add(new RequestParamMethodArgumentResolver(beanFactory, reactiveRegistry, true));
	if (supportDataBinding) {
		result.add(new ModelAttributeMethodArgumentResolver(reactiveRegistry, true));
	}

	return result;
}
 
Example 18
private static BeanDefinitionRegistry getRegistry(ConfigurableApplicationContext applicationContext) {
	if (applicationContext instanceof BeanDefinitionRegistry) {
		return ((BeanDefinitionRegistry) applicationContext);
	}
	return ((BeanDefinitionRegistry) applicationContext.getBeanFactory());
}
 
Example 19
Source Project: jeesupport   File: SessionFactoryRegistry.java    License: MIT License 4 votes vote down vote up
private AtomikosDataSourceBean createXADataSource(String _name) {
    String head = "jees.jdbs.config." + _name + ".";
    String type = CommonConfig.getString( head + "dbtype" );
    String bean = _name + "XADataSource";
    Properties xaProperties = new Properties();

    xaProperties.setProperty("user", CommonConfig.getString(head + "user"));
    xaProperties.setProperty("password", CommonConfig.getString(head + "password"));
    xaProperties.setProperty("url", CommonConfig.getString(head + "url"));

    BeanDefinitionBuilder beanDefinitionBuilder =
            BeanDefinitionBuilder.rootBeanDefinition(AbsXADataSource.class);

    // 这里没有列举AbstractDataSourceBean的所有可用属性
    if( type.equalsIgnoreCase( "mysql" ) ) {
        xaProperties.setProperty("pinGlobalTxToPhysicalConnection",
                CommonConfig.getString(head + "pinGlobalTxToPhysicalConnection", "true"));

        beanDefinitionBuilder.addPropertyValue("uniqueResourceName",
                CommonConfig.getString( head + "uniqueResourceName" ));
        beanDefinitionBuilder.addPropertyValue("xaDataSourceClassName",
                CommonConfig.getString( head + "xaDataSourceClassName" ) );

        beanDefinitionBuilder.addPropertyValue("xaProperties", xaProperties);

        beanDefinitionBuilder.addPropertyValue("maxPoolSize",
                CommonConfig.getString( head + "maxPoolSize", "1" ));
        beanDefinitionBuilder.addPropertyValue("minPoolSize",
                CommonConfig.getString( head + "minPoolSize", "1" ));
        beanDefinitionBuilder.addPropertyValue("maxIdleTime",
                CommonConfig.getString( head + "maxIdleTime", "60" ));

        beanDefinitionBuilder.addPropertyValue("poolSize", CommonConfig.getString( head + "poolSize", "1" ) );
    }

    ConfigurableApplicationContext context = (ConfigurableApplicationContext) CommonContextHolder.getApplicationContext();
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    beanFactory.registerBeanDefinition( bean, beanDefinitionBuilder.getBeanDefinition() );

    AbsXADataSource xaDataSource = CommonContextHolder.getBean( bean );
    log.debug("--创建AbsXADataSource[" + bean + "]。");



    return xaDataSource;
}
 
Example 20
Source Project: Milkomeda   File: WebContext.java    License: MIT License 2 votes vote down vote up
/**
 * 注册BeanDefinition
 * @param applicationContext    应用上下文
 * @param name                  bean name
 * @param clazz                 bean class
 * @param beanDefinition        BeanDefinition
 * @param <T>                   实体类型
 * @return  Bean
 */
public static <T> T registerBean(ConfigurableApplicationContext applicationContext, String name, Class<T> clazz, BeanDefinition beanDefinition) {
    BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
    beanFactory.registerBeanDefinition(name, beanDefinition);
    return applicationContext.getBean(name, clazz);
}