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

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#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: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithAutowiredValidator() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
Example 2
Source File: JGitEnvironmentRepositorySslTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test(expected = CertificateException.class)
public void selfSignedCertIsRejected() throws Throwable {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestConfiguration.class).properties(configServerProperties())
					.web(WebApplicationType.NONE).run();

	JGitEnvironmentRepository repository = context
			.getBean(JGitEnvironmentRepository.class);

	try {
		repository.findOne("bar", "staging", "master");
	}
	catch (Throwable e) {
		while (e.getCause() != null) {
			e = e.getCause();
			if (e instanceof CertificateException) {
				break;
			}
		}
		throw e;
	}
}
 
Example 3
Source File: StreamListenerWithConditionsTest.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedArgumentsWithConditionalClass() throws Exception {
	ConfigurableApplicationContext context = SpringApplication
			.run(TestPojoWithAnnotatedArguments.class, "--server.port=0");

	TestPojoWithAnnotatedArguments testPojoWithAnnotatedArguments = context
			.getBean(TestPojoWithAnnotatedArguments.class);
	Sink sink = context.getBean(Sink.class);
	String id = UUID.randomUUID().toString();
	sink.input().send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
			.setHeader("contentType", "application/json")
			.setHeader("testHeader", "testValue").setHeader("type", "foo").build());
	sink.input().send(MessageBuilder.withPayload("{\"bar\":\"foofoo" + id + "\"}")
			.setHeader("contentType", "application/json")
			.setHeader("testHeader", "testValue").setHeader("type", "bar").build());
	sink.input().send(MessageBuilder.withPayload("{\"bar\":\"foofoo" + id + "\"}")
			.setHeader("contentType", "application/json")
			.setHeader("testHeader", "testValue").setHeader("type", "qux").build());
	assertThat(testPojoWithAnnotatedArguments.receivedFoo).hasSize(1);
	assertThat(testPojoWithAnnotatedArguments.receivedFoo.get(0))
			.hasFieldOrPropertyWithValue("foo", "barbar" + id);
	assertThat(testPojoWithAnnotatedArguments.receivedBar).hasSize(1);
	assertThat(testPojoWithAnnotatedArguments.receivedBar.get(0))
			.hasFieldOrPropertyWithValue("bar", "foofoo" + id);
	context.close();
}
 
Example 4
Source File: SpringNamespaceExample.java    From opensharding-spi-impl-example with Apache License 2.0 5 votes vote down vote up
private static void processSeataTransaction(final ConfigurableApplicationContext applicationContext) {
    SeataTransactionalService transactionalService = applicationContext.getBean(SeataTransactionalService.class);
    transactionalService.initEnvironment();
    transactionalService.processSuccess();
    try {
        transactionalService.processFailure();
    } catch (final Exception ex) {
        transactionalService.printData();
    } finally {
        transactionalService.cleanEnvironment();
    }
}
 
Example 5
Source File: JCacheJavaConfigTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void emptyConfigSupport() {
	ConfigurableApplicationContext context =
			new AnnotationConfigApplicationContext(EmptyConfigSupportConfig.class);

	DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class);
	assertNotNull(cos.getCacheResolver());
	assertEquals(SimpleCacheResolver.class, cos.getCacheResolver().getClass());
	assertSame(context.getBean(CacheManager.class),
			((SimpleCacheResolver) cos.getCacheResolver()).getCacheManager());
	assertNull(cos.getExceptionCacheResolver());
	context.close();
}
 
Example 6
Source File: DestroyMethodInferenceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void beanMethods() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
	WithExplicitDestroyMethod c0 = ctx.getBean(WithExplicitDestroyMethod.class);
	WithLocalCloseMethod c1 = ctx.getBean("c1", WithLocalCloseMethod.class);
	WithLocalCloseMethod c2 = ctx.getBean("c2", WithLocalCloseMethod.class);
	WithInheritedCloseMethod c3 = ctx.getBean("c3", WithInheritedCloseMethod.class);
	WithInheritedCloseMethod c4 = ctx.getBean("c4", WithInheritedCloseMethod.class);
	WithInheritedCloseMethod c5 = ctx.getBean("c5", WithInheritedCloseMethod.class);
	WithNoCloseMethod c6 = ctx.getBean("c6", WithNoCloseMethod.class);
	WithLocalShutdownMethod c7 = ctx.getBean("c7", WithLocalShutdownMethod.class);
	WithInheritedCloseMethod c8 = ctx.getBean("c8", WithInheritedCloseMethod.class);
	WithDisposableBean c9 = ctx.getBean("c9", WithDisposableBean.class);

	assertThat(c0.closed, is(false));
	assertThat(c1.closed, is(false));
	assertThat(c2.closed, is(false));
	assertThat(c3.closed, is(false));
	assertThat(c4.closed, is(false));
	assertThat(c5.closed, is(false));
	assertThat(c6.closed, is(false));
	assertThat(c7.closed, is(false));
	assertThat(c8.closed, is(false));
	assertThat(c9.closed, is(false));
	ctx.close();
	assertThat("c0", c0.closed, is(true));
	assertThat("c1", c1.closed, is(true));
	assertThat("c2", c2.closed, is(true));
	assertThat("c3", c3.closed, is(true));
	assertThat("c4", c4.closed, is(true));
	assertThat("c5", c5.closed, is(true));
	assertThat("c6", c6.closed, is(false));
	assertThat("c7", c7.closed, is(true));
	assertThat("c8", c8.closed, is(false));
	assertThat("c9", c9.closed, is(true));
}
 
Example 7
Source File: JGitEnvironmentRepositorySslTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void selfSignedCertWithSkipSslValidationIsAccepted() {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestConfiguration.class)
					.properties(configServerProperties(
							"spring.cloud.config.server.git.skipSslValidation=true"))
					.web(WebApplicationType.NONE).run();

	JGitEnvironmentRepository repository = context
			.getBean(JGitEnvironmentRepository.class);
	repository.findOne("bar", "staging", "master");
}
 
Example 8
Source File: MSF4JSpringApplication.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * This will add a given service class to the running instance with given base path.
 *
 * @param configurableApplicationContext ConfigurableApplicationContext of running app
 * @param serviceClass                   Service class
 * @param basePath                       Base path to which the service get registered
 */
public SpringMicroservicesRunner addService(ConfigurableApplicationContext configurableApplicationContext,
                                            Class<?> serviceClass, String basePath) {
    ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner =
            new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) configurableApplicationContext);
    classPathBeanDefinitionScanner.scan(serviceClass.getPackage().getName());
    SpringMicroservicesRunner springMicroservicesRunner =
            configurableApplicationContext.getBean(SpringMicroservicesRunner.class);
    springMicroservicesRunner.deploy(basePath, configurableApplicationContext.getBean(serviceClass));
    return springMicroservicesRunner;
}
 
Example 9
Source File: MBeanExporterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testAutodetectNoMBeans() throws Exception {
	ConfigurableApplicationContext ctx = load("autodetectNoMBeans.xml");
	try {
		ctx.getBean("exporter");
	}
	finally {
		ctx.close();
	}
}
 
Example 10
Source File: AnnotationLazyInitMBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void lazyNaming() throws Exception {
	ConfigurableApplicationContext ctx =
			new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml");
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
		assertNotNull(server.getObjectInstance(oname));
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "TEST", name);
	}
	finally {
		ctx.close();
	}
}
 
Example 11
Source File: ReactorLoadBalancerClientAutoConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
void noCustomWebClientBuilders() {
	ConfigurableApplicationContext context = init(NoWebClientBuilder.class);
	final Map<String, WebClient.Builder> webClientBuilders = context
			.getBeansOfType(WebClient.Builder.class);

	then(webClientBuilders).hasSize(1);

	WebClient.Builder builder = context.getBean(WebClient.Builder.class);

	then(builder).isNotNull();
	then(getFilters(builder)).isNullOrEmpty();
}
 
Example 12
Source File: ExpressionCachingIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-11692
@SuppressWarnings("unchecked")
public void expressionIsCacheBasedOnActualMethod() {
	ConfigurableApplicationContext context =
			new AnnotationConfigApplicationContext(SharedConfig.class, Spr11692Config.class);

	BaseDao<User> userDao = (BaseDao<User>) context.getBean("userDao");
	BaseDao<Order> orderDao = (BaseDao<Order>) context.getBean("orderDao");

	userDao.persist(new User("1"));
	orderDao.persist(new Order("2"));

	context.close();
}
 
Example 13
Source File: BasePersistentWorkflowTest.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
public void testErrorHandlingWithWaitHook(String dsContext) throws Exception {
    assumeFalse(skipTests());
    final ConfigurableApplicationContext context = createContext(dsContext);
    cleanDB(context.getBean(DataSource.class));
    final PersistentScottyEngine engine = context.getBean(PersistentScottyEngine.class);
    try {
        engine.startup();
        final WorkflowInstanceDescr<Serializable> wfInstanceDescr = new WorkflowInstanceDescr<Serializable>("org.copperengine.regtest.test.persistent.ErrorWaitHookUnitTestWorkflow");
        wfInstanceDescr.setId(engine.createUUID());
        engine.run(wfInstanceDescr, null);
        Thread.sleep(3500);
        // check
        new RetryingTransaction<Void>(context.getBean(DataSource.class)) {
            @Override
            protected Void execute() throws Exception {
                Statement stmt = createStatement(getConnection());
                ResultSet rs = stmt.executeQuery("select * from COP_WORKFLOW_INSTANCE_ERROR");
                assertTrue(rs.next());
                assertEquals(wfInstanceDescr.getId(), rs.getString("WORKFLOW_INSTANCE_ID"));
                assertNotNull(rs.getString("EXCEPTION"));
                assertFalse(rs.next());
                rs.close();
                stmt.close();
                return null;
            }
        }.run();
    } finally {
        closeContext(context);
    }
    assertEquals(EngineState.STOPPED, engine.getEngineState());
    assertEquals(0, engine.getNumberOfWorkflowInstances());
}
 
Example 14
Source File: EnableJmsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void lazyComponent() {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			EnableJmsDefaultContainerFactoryConfig.class, LazyBean.class);
	JmsListenerContainerTestFactory defaultFactory =
			context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class);
	assertEquals(0, defaultFactory.getListenerContainers().size());

	context.getBean(LazyBean.class);  // trigger lazy resolution
	assertEquals(1, defaultFactory.getListenerContainers().size());
	MessageListenerTestContainer container = defaultFactory.getListenerContainers().get(0);
	assertTrue("Should have been started " + container, container.isStarted());
	context.close();  // close and stop the listeners
	assertTrue("Should have been stopped " + container, container.isStopped());
}
 
Example 15
Source File: BasePersistentWorkflowTest.java    From copper-engine with Apache License 2.0 4 votes vote down vote up
public void testWithConnectionBulkInsert(String dsContext) throws Exception {
    assumeFalse(skipTests());
    logger.info("running testWithConnectionBulkInsert");
    final int NUMB = 50;
    final ConfigurableApplicationContext context = createContext(dsContext);
    final DataSource ds = context.getBean(DataSource.class);
    cleanDB(ds);
    final PersistentScottyEngine engine = context.getBean(PersistentScottyEngine.class);
    engine.startup();
    final BackChannelQueue backChannelQueue = context.getBean(BackChannelQueue.class);
    try {
        assertEquals(EngineState.STARTED, engine.getEngineState());

        final List<Workflow<?>> list = new ArrayList<Workflow<?>>();
        for (int i = 0; i < NUMB; i++) {
            WorkflowFactory<?> wfFactory = engine.createWorkflowFactory(PersistentUnitTestWorkflow_NAME);
            Workflow<?> wf = wfFactory.newInstance();
            list.add(wf);
        }

        new RetryingTransaction<Void>(ds) {
            @Override
            protected Void execute() throws Exception {
                engine.run(list, getConnection());
                return null;
            }
        }.run();

        for (int i = 0; i < NUMB; i++) {
            WorkflowResult x = backChannelQueue.dequeue(DEQUEUE_TIMEOUT, TimeUnit.SECONDS);
            assertNotNull(x);
            assertNull(x.getResult());
            assertNull(x.getException());
        }
    } finally {
        closeContext(context);
    }
    assertEquals(EngineState.STOPPED, engine.getEngineState());
    assertEquals(0, engine.getNumberOfWorkflowInstances());

}
 
Example 16
Source File: TraceWebFluxTests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Test
public void should_instrument_web_filter() throws Exception {
	// setup
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TraceWebFluxTests.Config.class)
					.web(WebApplicationType.REACTIVE)
					.properties("server.port=0", "spring.jmx.enabled=false",
							"spring.sleuth.web.skipPattern=/skipped",
							"spring.application.name=TraceWebFluxTests",
							"security.basic.enabled=false",
							"management.security.enabled=false")
					.run();
	TestSpanHandler spans = context.getBean(TestSpanHandler.class);
	int port = context.getBean(Environment.class).getProperty("local.server.port",
			Integer.class);
	Controller2 controller2 = context.getBean(Controller2.class);
	clean(spans, controller2);

	// when
	ClientResponse response = whenRequestIsSent(port, "/api/c2/10");
	// then
	thenSpanWasReportedWithTags(spans, response);
	clean(spans, controller2);

	// when
	response = whenRequestIsSent(port, "/api/fn/20");
	// then
	thenFunctionalSpanWasReportedWithTags(spans, response);
	spans.clear();

	// when
	ClientResponse nonSampledResponse = whenNonSampledRequestIsSent(port);
	// then
	thenNoSpanWasReported(spans, nonSampledResponse, controller2);
	spans.clear();

	// when
	ClientResponse skippedPatternResponse = whenRequestIsSentToSkippedPattern(port);
	// then
	thenNoSpanWasReported(spans, skippedPatternResponse, controller2);

	// cleanup
	context.close();
}
 
Example 17
Source File: EnableCachingIntegrationTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void fooServiceWithInterface() {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(FooConfig.class);
	FooService service = context.getBean(FooService.class);
	fooGetSimple(context, service);
}
 
Example 18
Source File: AnnotationDrivenEventListenerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
private EventCollector getEventCollector(ConfigurableApplicationContext context) {
	return context.getBean(EventCollector.class);
}
 
Example 19
Source File: SpringJdbcDemo.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 4 votes vote down vote up
public static void main(String[] args) {
	ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
	TransferService transferService = applicationContext.getBean(TransferService.class);
	transferService.transfer(50000l, 1000l, 2000l);
	applicationContext.close();
}
 
Example 20
Source File: ClientDemoApplication.java    From dubbo-arthas-demo with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
		ConfigurableApplicationContext context = SpringApplication.run(ClientDemoApplication.class, args);

		ClientDemoApplication application = context.getBean(ClientDemoApplication.class);

//		 application.loop();
	}