org.springframework.context.ConfigurableApplicationContext#getBean ( )源码实例Demo

下面列出了org.springframework.context.ConfigurableApplicationContext#getBean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
}
 
@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;
	}
}
 
@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();
}
 
@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();
}
 
源代码5 项目: java-technology-stack   文件: EnableJmsTests.java
@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());
}
 
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());
}
 
@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();
}
 
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();
    }
}
 
@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();
	}
}
 
源代码10 项目: java-technology-stack   文件: MBeanExporterTests.java
@Test
public void testAutodetectNoMBeans() throws Exception {
	ConfigurableApplicationContext ctx = load("autodetectNoMBeans.xml");
	try {
		ctx.getBean("exporter");
	}
	finally {
		ctx.close();
	}
}
 
源代码11 项目: msf4j   文件: MSF4JSpringApplication.java
/**
 * 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;
}
 
@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");
}
 
@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));
}
 
@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();
}
 
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();
}
 
private EventCollector getEventCollector(ConfigurableApplicationContext context) {
	return context.getBean(EventCollector.class);
}
 
@Test
public void fooServiceWithInterface() {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(FooConfig.class);
	FooService service = context.getBean(FooService.class);
	fooGetSimple(context, service);
}
 
源代码18 项目: spring-cloud-sleuth   文件: TraceWebFluxTests.java
@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();
}
 
源代码19 项目: copper-engine   文件: BasePersistentWorkflowTest.java
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());

}
 
源代码20 项目: dubbo-arthas-demo   文件: ClientDemoApplication.java
public static void main(String[] args) throws IOException, InterruptedException {
		ConfigurableApplicationContext context = SpringApplication.run(ClientDemoApplication.class, args);

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

//		 application.loop();
	}