Java Code Examples for org.springframework.context.support.AbstractApplicationContext#getBean()

The following examples show how to use org.springframework.context.support.AbstractApplicationContext#getBean() . 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: UserProducerApp.java    From Spring with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            ServiceConfig.class, JmsCommonConfig.class, JmsProducerConfig.class);
    UserService userService = context.getBean(UserService.class);
    UserSender userSender = context.getBean(UserSender.class);

    List<User> users = userService.findAll();

    assertTrue(users.size() > 0);
    for (User user : users) {
        userSender.sendMessage(user);
    }

    log.info("User message sent. Wait for confirmation...");

    System.in.read();

    context.close();
}
 
Example 2
Source File: WebApplicationContextLoader.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Provides a static, single instance of the application context.  This method can be
 * called repeatedly.
 * <p/>
 * If the configuration requested differs from one used previously, then the previously-created
 * context is shut down.
 * 
 * @return Returns an application context for the given configuration
 */
public synchronized static ConfigurableApplicationContext getApplicationContext(ServletContext servletContext, String[] configLocations)
{
	AbstractApplicationContext ctx = (AbstractApplicationContext)BaseApplicationContextHelper.getApplicationContext(configLocations);
	
	CmisServiceFactory factory = (CmisServiceFactory)ctx.getBean("CMISServiceFactory");
	
	DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(ctx.getBeanFactory());
	GenericWebApplicationContext gwac = new GenericWebApplicationContext(dlbf);
	servletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, gwac);
       servletContext.setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory);
	gwac.setServletContext(servletContext);
	gwac.refresh();

	return gwac;
}
 
Example 3
Source File: GridServiceInjectionSpringResourceTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @throws Exception If failed.
 */
private void startNodes() throws Exception {
    AbstractApplicationContext ctxSpring = new FileSystemXmlApplicationContext(springCfgFileOutTmplName + 0);

    // We have to deploy Services for service is available at the bean creation time for other nodes.
    Ignite ignite = (Ignite)ctxSpring.getBean("testIgnite");

    ignite.services().deployMultiple(SERVICE_NAME, new DummyServiceImpl(), NODES, 1);

    // Add other nodes.
    for (int i = 1; i < NODES; ++i)
        new FileSystemXmlApplicationContext(springCfgFileOutTmplName + i);

    assertEquals(NODES, G.allGrids().size());
    assertEquals(NODES, ignite.cluster().nodes().size());
}
 
Example 4
Source File: EventFiringObjectFactory.java    From java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This method makes an event firing object.
 *
 * @param t an original {@link Object} that is
 *               supposed to be listenable
 * @param driver an instance of {@link org.openqa.selenium.WebDriver}
 * @param listeners is a collection of {@link io.appium.java_client.events.api.Listener} that
 *                  is supposed to be used for the event firing
 * @param <T> T
 * @return an {@link Object} that fires events
 */
@SuppressWarnings("unchecked")
public static <T> T getEventFiringObject(T t, WebDriver driver, Collection<Listener> listeners) {
    final List<Listener> listenerList = new ArrayList<>();

    for (Listener listener : ServiceLoader.load(
            Listener.class)) {
        listenerList.add(listener);
    }

    listeners.stream().filter(listener -> !listenerList.contains(listener)).forEach(listenerList::add);

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            DefaultBeanConfiguration.class);
    return (T) context.getBean(
            DefaultBeanConfiguration.LISTENABLE_OBJECT, t, driver, listenerList, context);
}
 
Example 5
Source File: SpringProcessApplicationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostDeployWithNestedContext() {
  /*
   * This test case checks if the process application deployment is done when
   * application context is refreshed, but not when child contexts are
   * refreshed.
   * 
   * As a side test it checks if events thrown in the PostDeploy-method are
   * catched by the main application context.
   */

  AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
      "org/camunda/bpm/engine/spring/test/application/PostDeployWithNestedContext-context.xml");
  applicationContext.start();

  // lookup the process application spring bean:
  PostDeployWithNestedContext processApplication = applicationContext.getBean("customProcessApplicaiton", PostDeployWithNestedContext.class);

  Assert.assertFalse(processApplication.isDeployOnChildRefresh());
  Assert.assertTrue(processApplication.isLateEventTriggered());

  processApplication.undeploy();
  applicationContext.close();
}
 
Example 6
Source File: UserConsumerApp.java    From Spring with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            JmsCommonConfig.class, JmsConsumerConfig.class);

    UserReceiver userReceiver = context.getBean(UserReceiver.class);
    assertNotNull(userReceiver);
    log.info("Waiting for user ...");
    System.in.read();
    context.close();
}
 
Example 7
Source File: WebApplicationContextLoader.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
public synchronized static ConfigurableApplicationContext getApplicationContext(ServletContext servletContext, final String[] configLocations,
		final String[] classLocations) throws IOException
{
	final AbstractApplicationContext ctx = (AbstractApplicationContext)BaseApplicationContextHelper.getApplicationContext(configLocations, classLocations);
	DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(ctx.getBeanFactory());
	GenericWebApplicationContext gwac = new GenericWebApplicationContext(dlbf);
	CmisServiceFactory factory = (CmisServiceFactory)ctx.getBean("CMISServiceFactory");

	servletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, gwac);
       servletContext.setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory);
	gwac.setServletContext(servletContext);
	gwac.refresh();

	return gwac;
}
 
Example 8
Source File: AbstractCosmosConfigurationIT.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
@Test(expected = NoSuchBeanDefinitionException.class)
public void defaultObjectMapperBeanNotExists() {
    final AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            TestCosmosConfiguration.class);

    context.getBean(ObjectMapper.class);
}
 
Example 9
Source File: SecurityDomainRouterFactory.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public VertxSecurityDomainHandler create(Domain domain) {
    if (domain.isEnabled()) {
        AbstractApplicationContext internalApplicationContext = createApplicationContext(domain);
        startComponents(internalApplicationContext);
        VertxSecurityDomainHandler handler = internalApplicationContext.getBean(VertxSecurityDomainHandler.class);
        return handler;
    } else {
        logger.warn("Domain is disabled !");
        return null;
    }
}
 
Example 10
Source File: AnnotationRequired.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-annotation.xml");

	AnnotationRequired annotationRequired = (AnnotationRequired) ctx.getBean("annotationRequired");
	log.debug("name: {}", annotationRequired.getName());
	ctx.close();
}
 
Example 11
Source File: AnnotationQualifier.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-annotation.xml");

	AnnotationQualifier annotationQualifier = (AnnotationQualifier) ctx.getBean("annotationQualifier");

	log.debug("type: {}, name: {}", annotationQualifier.getFieldA().getClass(),
		annotationQualifier.getFieldA().getName());

	log.debug("type: {}, name: {}", annotationQualifier.getFieldB().getClass(),
		annotationQualifier.getFieldB().getName());
	ctx.close();
}
 
Example 12
Source File: AnnotationInject.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-annotation.xml");
	AnnotationInject annotationInject = (AnnotationInject) ctx.getBean("annotationInject");

	log.debug("type: {}, name: {}", annotationInject.getFieldA().getClass(),
		annotationInject.getFieldA().getName());

	log.debug("type: {}, name: {}", annotationInject.getFieldB().getClass(),
		annotationInject.getFieldB().getName());

	log.debug("type: {}, name: {}", annotationInject.getFieldC().getClass(),
		annotationInject.getFieldC().getName());

	ctx.close();
}
 
Example 13
Source File: AnnotationPostConstructAndPreDestroy.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-annotation.xml");
	AnnotationPostConstructAndPreDestroy annotationPostConstructAndPreDestroy =
		(AnnotationPostConstructAndPreDestroy) ctx
			.getBean("annotationPostConstructAndPreDestroy");
	log.debug("call main method");
	ctx.close();
}
 
Example 14
Source File: SpringBeanContext.java    From ob1k with Apache License 2.0 4 votes vote down vote up
public <T> T getBean(final String ctxName, final Class<T> type) {
  final AbstractApplicationContext context = contexts.get(ctxName);
  Objects.requireNonNull(context, "Context not found for name '" + ctxName + "'");
  return context.getBean(type);
}
 
Example 15
Source File: PrototypeBeanInjectionIntegrationTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void givenPrototypeInjection_WhenProvider_ThenNewInstanceReturn() {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    SingletonProviderBean firstContext = context.getBean(SingletonProviderBean.class);
    SingletonProviderBean secondContext = context.getBean(SingletonProviderBean.class);

    PrototypeBean firstInstance = firstContext.getPrototypeInstance();
    PrototypeBean secondInstance = secondContext.getPrototypeInstance();

    Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
 
Example 16
Source File: LocalSagaTransactionStarter.java    From seata-samples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] {"spring/seata-saga.xml"});

        StateMachineEngine stateMachineEngine = (StateMachineEngine) applicationContext.getBean("stateMachineEngine");

        transactionCommittedDemo(stateMachineEngine);

        transactionCompensatedDemo(stateMachineEngine);

        new ApplicationKeeper(applicationContext).keep();
    }
 
Example 17
Source File: PrototypeFunctionBeanIntegrationTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void givenPrototypeInjection_WhenFunction_ThenNewInstanceReturn() {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfigFunctionBean.class);

    SingletonFunctionBean firstContext = context.getBean(SingletonFunctionBean.class);
    SingletonFunctionBean secondContext = context.getBean(SingletonFunctionBean.class);

    PrototypeBean firstInstance = firstContext.getPrototypeInstance("instance1");
    PrototypeBean secondInstance = secondContext.getPrototypeInstance("instance2");

    Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
 
Example 18
Source File: PrototypeBeanInjectionIntegrationTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    SingletonObjectFactoryBean firstContext = context.getBean(SingletonObjectFactoryBean.class);
    SingletonObjectFactoryBean secondContext = context.getBean(SingletonObjectFactoryBean.class);

    PrototypeBean firstInstance = firstContext.getPrototypeInstance();
    PrototypeBean secondInstance = secondContext.getPrototypeInstance();

    Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
 
Example 19
Source File: DrawingApp.java    From Spring with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

		final AbstractApplicationContext beanFactory = new ClassPathXmlApplicationContext("src/main/resources/jb/_2_scope_lifecycle/spring.xml");
		beanFactory.registerShutdownHook(); // enable destroying beans (@PreDestroy, implements DisposableBean)

		final Holder holder = beanFactory.getBean("holder", Holder.class);
		System.out.println(holder.getDependency().getName().equals("spring-oore"));  //true

		final Triangle triangleSingleton1 = (Triangle) beanFactory.getBean("triangleSingleton");
		final Triangle triangleSingleton2 = (Triangle) beanFactory.getBean("triangleSingleton");
		System.out.println((triangleSingleton1 == triangleSingleton2));  //true

		final Triangle trianglePrototype1 = (Triangle) beanFactory.getBean("trianglePrototype");
		final Triangle trianglePrototype2 = (Triangle) beanFactory.getBean("trianglePrototype");
		System.out.println((trianglePrototype1 == trianglePrototype2));  //false

		final TriangleAware triangleAware = (TriangleAware) beanFactory.getBean("triangleAware");
		triangleAware.draw();

		final TriangleInheritance triangleInheritance1 = (TriangleInheritance) beanFactory.getBean("triangle1");
		triangleInheritance1.draw();

		final TriangleInheritance triangleInheritance2 = (TriangleInheritance) beanFactory.getBean("triangle2");
		triangleInheritance2.draw();

		final TriangleLifecycle triangleLifecycle = (TriangleLifecycle) beanFactory.getBean("triangleLifecycle");

		final Point pointWithProperty = (Point) beanFactory.getBean("pointWithProperty");
		System.out.println(pointWithProperty);

	}
 
Example 20
Source File: DubboSagaTransactionStarter.java    From seata-samples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] {"spring/seata-saga.xml", "spring/seata-dubbo-reference.xml"});

        StateMachineEngine stateMachineEngine = (StateMachineEngine) applicationContext.getBean("stateMachineEngine");

        transactionCommittedDemo(stateMachineEngine);

        transactionCompensatedDemo(stateMachineEngine);

        new ApplicationKeeper(applicationContext).keep();
    }