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

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

public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(FormatterBootstrap.class)
                .web(WebApplicationType.NONE)  // 非 Web 应用
//                 .properties("formatter.enabled=true") // 配置默认属性, "=" 前后不能有空格
                .run(args);                    // 运行
        // 待格式化对象
        Map<String, Object> data = new HashMap<>();
        data.put("name", "小马哥");
        // 获取 Formatter 来自于 FormatterAutoConfiguration
        Map<String, Formatter> beans = context.getBeansOfType(Formatter.class);
        if (beans.isEmpty()) { // 如果 Bean 不存在,抛出异常
            throw new NoSuchBeanDefinitionException(Formatter.class);
        }
        beans.forEach((beanName, formatter) -> {
            System.out.printf("[Bean name : %s] %s.format(data) : %s\n", beanName, formatter.getClass().getSimpleName(),
                    formatter.format(data));
        });

        //  关闭当前上下文
        context.close();
    }
 
源代码2 项目: line-bot-sdk-java   文件: Application.java
void run(final ConfigurableApplicationContext context) throws Exception {
    final Map<String, CliCommand> commandMap = context.getBeansOfType(CliCommand.class);
    if (commandMap.isEmpty()) {
        log.warn("No command resolved. Available commands are follows.");
        printSupportCommand();
        return;
    }
    if (commandMap.size() > 1) {
        throw new RuntimeException("Multiple command matching. Maybe bug.");
    }

    final CliCommand command = commandMap.values().iterator().next();

    log.info("\"--command\" resolved to > {}", command.getClass());

    command.execute();
}
 
@Test
public void multipleRestTemplates() {
	ConfigurableApplicationContext context = init(TwoRestTemplates.class);
	final Map<String, RestTemplate> restTemplates = context
			.getBeansOfType(RestTemplate.class);

	then(restTemplates).isNotNull();
	Collection<RestTemplate> templates = restTemplates.values();
	then(templates).hasSize(2);

	TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class);

	then(two.loadBalanced).isNotNull();
	assertLoadBalanced(two.loadBalanced);

	then(two.nonLoadBalanced).isNotNull();
	then(two.nonLoadBalanced.getInterceptors()).isEmpty();
}
 
@Test
void loadBalancerFilterAddedToWebClientBuilder() {
	ConfigurableApplicationContext context = init(OneWebClientBuilder.class);
	final Map<String, WebClient.Builder> webClientBuilders = context
			.getBeansOfType(WebClient.Builder.class);

	then(webClientBuilders).isNotNull().hasSize(1);
	WebClient.Builder webClientBuilder = webClientBuilders.values().iterator().next();
	then(webClientBuilder).isNotNull();

	assertLoadBalanced(webClientBuilder,
			ReactorLoadBalancerExchangeFilterFunction.class);

	final Map<String, OneWebClientBuilder.TestService> testServiceMap = context
			.getBeansOfType(OneWebClientBuilder.TestService.class);
	then(testServiceMap).isNotNull().hasSize(1);
	OneWebClientBuilder.TestService testService = testServiceMap.values().stream()
			.findFirst().get();
	assertLoadBalanced(testService.webClient,
			ReactorLoadBalancerExchangeFilterFunction.class);
}
 
@Test
void loadBalancerFilterAddedOnlyToLoadBalancedWebClientBuilder() {
	ConfigurableApplicationContext context = init(TwoWebClientBuilders.class);
	final Map<String, WebClient.Builder> webClientBuilders = context
			.getBeansOfType(WebClient.Builder.class);

	then(webClientBuilders).hasSize(2);

	TwoWebClientBuilders.Two two = context.getBean(TwoWebClientBuilders.Two.class);

	then(two.loadBalanced).isNotNull();
	assertLoadBalanced(two.loadBalanced,
			ReactorLoadBalancerExchangeFilterFunction.class);

	then(two.nonLoadBalanced).isNotNull();
	then(getFilters(two.nonLoadBalanced)).isNullOrEmpty();
}
 
@Test
public void multipleRestTemplates() {
	ConfigurableApplicationContext context = init(TwoRestTemplates.class);
	final Map<String, AsyncRestTemplate> restTemplates = context
			.getBeansOfType(AsyncRestTemplate.class);

	then(restTemplates).isNotNull();
	Collection<AsyncRestTemplate> templates = restTemplates.values();
	then(templates).hasSize(2);

	TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class);

	then(two.loadBalanced).isNotNull();
	assertLoadBalanced(two.loadBalanced);

	then(two.nonLoadBalanced).isNotNull();
	then(two.nonLoadBalanced.getInterceptors()).isEmpty();
}
 
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.consul.enabled=true",
            "--spring.cloud.consul.config.enabled=false",
            "--spring.cloud.consul.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--spring.main.allow-bean-definition-overriding=true"
        );

    // TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
    //  is released that supports Spring Boot 2.1 more properly

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ServiceDefinitionToConsulRegistration.class::isInstance)).isTrue();
    } finally {
        context.close();
    }
}
 
@Test
public void testConsulServerToServiceDefinition() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.consul.enabled=true",
            "--spring.cloud.consul.config.enabled=false",
            "--spring.cloud.consul.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--spring.main.allow-bean-definition-overriding=true"
        );

    // TODO: Remove --spring.main.allow-bean-definition-overriding=true when new version of spring-cloud
    //  is released that supports Spring Boot 2.1 more properly

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ConsulServerToServiceDefinition.class::isInstance)).isTrue();
    } finally {
        context.close();
    }
}
 
@Test
public void testServiceDefinitionToConsulRegistration() throws Exception {
    final ZookeeperServer server = new ZookeeperServer(temporaryFolder.newFolder(testName.getMethodName()));

    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.zookeeper.enabled=true",
            "--spring.cloud.zookeeper.connect-string=" + server.connectString(),
            "--spring.cloud.zookeeper.config.enabled=false",
            "--spring.cloud.zookeeper.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false"
        );

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ServiceDefinitionToZookeeperRegistration.class::isInstance)).isTrue();
    } finally {
        // shutdown spring context
        context.close();

        // shutdown zookeeper
        server.shutdown();
    }
}
 
@Test
public void testZookeeperServerToServiceDefinition() throws Exception {
    final ZookeeperServer server = new ZookeeperServer(temporaryFolder.newFolder(testName.getMethodName()));

    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.zookeeper.enabled=true",
            "--spring.cloud.zookeeper.connect-string=" + server.connectString(),
            "--spring.cloud.zookeeper.config.enabled=false",
            "--spring.cloud.zookeeper.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false"
        );

    try {
        Map<String, Converter> converters = context.getBeansOfType(Converter.class);

        assertThat(converters).isNotNull();
        assertThat(converters.values().stream().anyMatch(ZookeeperServerToServiceDefinition.class::isInstance)).isTrue();
    } finally {

        // shutdown spring context
        context.close();

        // shutdown zookeeper
        server.shutdown();
    }
}
 
@Test
public void camelContextShouldBeStartedLastAndStoppedFirst() {
    final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
        CamelAutoConfiguration.class, Beans.class);

    final CamelContext camelContext = context.getBean(CamelContext.class);
    final Map<String, TestState> testStates = context.getBeansOfType(TestState.class);

    assertThat(camelContext.isStarted()).as("Camel context should be started").isTrue();

    context.close();

    assertThat(camelContext.isStopped()).as("Camel context should be stopped").isTrue();
    testStates.values().stream().forEach(TestState::assertValid);
}
 
private void assertLoadBalanced(ConfigurableApplicationContext context,
		Class delegateClass) {
	Map<String, FeignBlockingLoadBalancerClient> beans = context
			.getBeansOfType(FeignBlockingLoadBalancerClient.class);
	assertThat(beans).as("Missing bean of type %s", delegateClass).hasSize(1);
	assertThat(beans.get("feignClient").getDelegate()).isInstanceOf(delegateClass);
}
 
public static void main(String[] args) {
    // 注册当前引导类作为 Configuration Class
    ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(TransactionalServiceBeanBootstrap.class);
    // 获取所有 TransactionalServiceBean 类型 Bean,其中 Key 为 Bean 名称
    Map<String, TransactionalServiceBean> beansMap = context.getBeansOfType(TransactionalServiceBean.class);
    beansMap.forEach((beanName, bean) -> {
        System.out.printf("Bean 名称 : %s , 对象 : %s\n", beanName, bean);
        bean.save();
    });
    context.close();
}
 
@Test
public void restTemplateGetsLoadBalancerInterceptor() {
	ConfigurableApplicationContext context = init(OneRestTemplate.class);
	final Map<String, RestTemplate> restTemplates = context
			.getBeansOfType(RestTemplate.class);

	then(restTemplates).isNotNull();
	then(restTemplates.values()).hasSize(1);
	RestTemplate restTemplate = restTemplates.values().iterator().next();
	then(restTemplate).isNotNull();

	assertLoadBalanced(restTemplate);
}
 
@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();
}
 
@Test
public void restTemplateGetsLoadBalancerInterceptor() {
	ConfigurableApplicationContext context = init(OneRestTemplate.class);
	final Map<String, AsyncRestTemplate> restTemplates = context
			.getBeansOfType(AsyncRestTemplate.class);

	then(restTemplates).isNotNull();
	then(restTemplates.values()).hasSize(1);
	AsyncRestTemplate restTemplate = restTemplates.values().iterator().next();
	then(restTemplate).isNotNull();

	assertLoadBalanced(restTemplate);
}
 
private void assertThatOneBeanPresent(ConfigurableApplicationContext context,
		Class<?> beanClass) {
	Map<String, ?> beans = context.getBeansOfType(beanClass);
	assertThat(beans).as("Missing bean of type %s", beanClass).hasSize(1);
}
 
@DataProvider(value = {
        "MANUAL_IMPORT_ONLY",
        "COMPONENT_SCAN_ONLY",
        "BOTH_MANUAL_AND_COMPONENT_SCAN"
})
@Test
public void component_test(ComponentTestSetup componentTestSetup) {
    // given
    int serverPort = findFreePort();
    Class<?> mainClass = componentTestSetup.mainClass;

    ConfigurableApplicationContext serverAppContext = SpringApplication.run(mainClass,
            "--server.port=" + serverPort);

    try {
        // when
        WingtipsSpringBoot2WebfluxConfiguration
                config = serverAppContext.getBean(WingtipsSpringBoot2WebfluxConfiguration.class);
        WingtipsSpringBoot2WebfluxProperties props =
                serverAppContext.getBean(WingtipsSpringBoot2WebfluxProperties.class);
        String[] someComponentScannedClassBeanNames =
                serverAppContext.getBeanNamesForType(SomeComponentScannedClass.class);

        // then
        // Sanity check that we component scanned (or not) as appropriate.
        if (componentTestSetup.expectComponentScannedObjects) {
            assertThat(someComponentScannedClassBeanNames).isNotEmpty();
        } else {
            assertThat(someComponentScannedClassBeanNames).isEmpty();
        }

        // WingtipsSpringBoot2WebfluxConfiguration and WingtipsSpringBoot2WebfluxProperties should be available as
        //      beans, and the config should use the same props we received.
        assertThat(config).isNotNull();
        assertThat(props).isNotNull();
        assertThat(config.wingtipsProperties).isSameAs(props);

        // The config should not have any custom WingtipsSpringWebfluxWebFilter. Spring will populate
        //      the config.customSpringWebfluxWebFilter field with whatever wingtipsSpringWebfluxWebFilter()
        //      produces - so they should be the same.
        Map<String, WingtipsSpringWebfluxWebFilter> filtersFromSpring =
                serverAppContext.getBeansOfType(WingtipsSpringWebfluxWebFilter.class);
        assertThat(filtersFromSpring).isEqualTo(
                Collections.singletonMap("wingtipsSpringWebfluxWebFilter", config.customSpringWebfluxWebFilter)
        );
    } finally {
        Schedulers.removeExecutorServiceDecorator(WingtipsReactorInitializer.WINGTIPS_SCHEDULER_KEY);
        SpringApplication.exit(serverAppContext);
    }
}
 
@Test
public void component_test_with_custom_WingtipsSpringWebfluxWebFilter() {
    // given
    int serverPort = findFreePort();

    ConfigurableApplicationContext serverAppContext = SpringApplication.run(
            ComponentTestMainWithCustomWingtipsWebFilter.class,
            "--server.port=" + serverPort
    );

    try {
        // when
        WingtipsSpringBoot2WebfluxConfiguration
                config = serverAppContext.getBean(WingtipsSpringBoot2WebfluxConfiguration.class);
        WingtipsSpringBoot2WebfluxProperties props =
                serverAppContext.getBean(WingtipsSpringBoot2WebfluxProperties.class);
        String[] someComponentScannedClassBeanNames =
                serverAppContext.getBeanNamesForType(SomeComponentScannedClass.class);

        // then
        // Sanity check that we component scanned (or not) as appropriate. This particular component test does
        //      include component scanning.
        assertThat(someComponentScannedClassBeanNames).isNotEmpty();

        // WingtipsSpringBoot2WebfluxConfiguration and WingtipsSpringBoot2WebfluxProperties should be available as
        //      beans, and the config should use the same props we received.
        assertThat(config).isNotNull();
        assertThat(props).isNotNull();
        assertThat(config.wingtipsProperties).isSameAs(props);

        // Finally, the thing this test is verifying: the config's custom filter should be the same one from the
        //      component test main class, and it should be the one that Spring exposes.
        assertThat(config.customSpringWebfluxWebFilter)
                .isSameAs(ComponentTestMainWithCustomWingtipsWebFilter.customFilter);
        Map<String, WingtipsSpringWebfluxWebFilter> filtersFromSpring =
                serverAppContext.getBeansOfType(WingtipsSpringWebfluxWebFilter.class);
        assertThat(filtersFromSpring).isEqualTo(
                Collections.singletonMap("customFilter", ComponentTestMainWithCustomWingtipsWebFilter.customFilter)
        );
    } finally {
        SpringApplication.exit(serverAppContext);
    }
}