org.springframework.context.annotation.AnnotationConfigApplicationContext Java Examples

The following examples show how to use org.springframework.context.annotation.AnnotationConfigApplicationContext. 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: SoftwareCatalogHarness.java    From waltz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    SoftwareCatalogService softwareCatalogService = ctx.getBean(SoftwareCatalogService.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);


    EntityReference ref = ImmutableEntityReference.builder()
            .kind(EntityKind.ORG_UNIT)
            .id(20L)
            .build();

    IdSelectionOptions options = IdSelectionOptions.mkOpts(ref, HierarchyQueryScope.CHILDREN);

    SoftwareSummaryStatistics stats = softwareCatalogService.calculateStatisticsForAppIdSelector(options);
    System.out.println("stats:"+stats);
}
 
Example #2
Source File: FeignClientFactoryTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testChildContexts() {
	AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
	parent.refresh();
	FeignContext context = new FeignContext();
	context.setApplicationContext(parent);
	context.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class),
			getSpec("bar", BarConfig.class)));

	Foo foo = context.getInstance("foo", Foo.class);
	assertThat(foo).as("foo was null").isNotNull();

	Bar bar = context.getInstance("bar", Bar.class);
	assertThat(bar).as("bar was null").isNotNull();

	Bar foobar = context.getInstance("foo", Bar.class);
	assertThat(foobar).as("bar was not null").isNull();
}
 
Example #3
Source File: ConfigurationBeanNameTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void registerOuterConfig_withBeanNameGenerator() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.setBeanNameGenerator(new AnnotationBeanNameGenerator() {
		@Override
		public String generateBeanName(
				BeanDefinition definition, BeanDefinitionRegistry registry) {
			return "custom-" + super.generateBeanName(definition, registry);
		}
	});
	ctx.register(A.class);
	ctx.refresh();
	assertThat(ctx.containsBean("custom-outer"), is(true));
	assertThat(ctx.containsBean("custom-imported"), is(true));
	assertThat(ctx.containsBean("custom-nested"), is(true));
	assertThat(ctx.containsBean("nestedBean"), is(true));
}
 
Example #4
Source File: OnceApplicationContextEventListenerTest.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
private ConfigurableApplicationContext createContext(int levels, boolean listenersAsBean) {

        if (levels < 1) {
            return null;
        }

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        if (listenersAsBean) {
            context.register(MyContextEventListener.class);
        } else {
            context.addApplicationListener(new MyContextEventListener(context));
        }

        context.setParent(createContext(levels - 1, listenersAsBean));

        context.refresh();

        return context;
    }
 
Example #5
Source File: UnionHarness.java    From waltz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);

    appGroupDao_findRelatedByApplicationId(ctx);
    appGroupDao_search(ctx);
    appIdSelectorFactory_mkForActor(ctx);
    appIdSelectorFactory_mkForAppGroup(ctx);
    appIdSelectorFactory_mkForDataType(ctx);
    appIdSelectorFactory_mkForFlowDiagram(ctx);
    connectionComplexityDao_findCounts(ctx);
    dataTypeUsageDao_recalculateForAllApplications(ctx);
    entityNameResolver_resolve(ctx);
    entityRelationshipDao_tallyRelationshipsInvolving(ctx);
    involvementDao_findAllApplicationsByEmployeeId(ctx);
    licenceDao_countApplications(ctx);
    logicalDataElementSearch_search(ctx);
    measurableIdSelectorFactory_mkForFlowDiagram(ctx);
    organisationalUnitDao_findImmediateHierarchy(ctx);
    physicalFlowDao_findByEntityRef(ctx);
}
 
Example #6
Source File: RSocketClientToServerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@BeforeClass
@SuppressWarnings("ConstantConditions")
public static void setupOnce() {
	context = new AnnotationConfigApplicationContext(ServerConfig.class);

	server = RSocketFactory.receive()
			.addServerPlugin(interceptor)
			.frameDecoder(PayloadDecoder.ZERO_COPY)
			.acceptor(context.getBean(MessageHandlerAcceptor.class))
			.transport(TcpServerTransport.create("localhost", 7000))
			.start()
			.block();

	requester = RSocketRequester.builder()
			.rsocketFactory(factory -> factory.frameDecoder(PayloadDecoder.ZERO_COPY))
			.rsocketStrategies(context.getBean(RSocketStrategies.class))
			.connectTcp("localhost", 7000)
			.block();
}
 
Example #7
Source File: ContextResourceLoaderAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void createResourceLoader_withoutExecutorSettings_executorConfigured() {

	// Arrange
	this.context = new AnnotationConfigApplicationContext();
	this.context.register(ContextResourceLoaderAutoConfiguration.class);

	// Act
	this.context.refresh();

	// Assert
	SimpleStorageProtocolResolver simpleStorageProtocolResolver = (SimpleStorageProtocolResolver) this.context
			.getProtocolResolvers().iterator().next();
	SyncTaskExecutor taskExecutor = (SyncTaskExecutor) ReflectionTestUtils
			.getField(simpleStorageProtocolResolver, "taskExecutor");
	assertThat(taskExecutor).isNotNull();
}
 
Example #8
Source File: JavaConfigPlaceholderTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplicationPropertySourceWithValueInjectedAsConstructorArgs() throws Exception {
  int someTimeout = 1000;
  int someBatch = 2000;

  Config config = mock(Config.class);
  when(config.getProperty(eq(TIMEOUT_PROPERTY), anyString())).thenReturn(String.valueOf(someTimeout));
  when(config.getProperty(eq(BATCH_PROPERTY), anyString())).thenReturn(String.valueOf(someBatch));

  mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config);

  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig7.class);

  TestJavaConfigBean3 bean = context.getBean(TestJavaConfigBean3.class);

  assertEquals(someTimeout, bean.getTimeout());
  assertEquals(someBatch, bean.getBatch());
}
 
Example #9
Source File: SpringbatchPartitionerApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(final String[] args) {
    // Spring Java config
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(SpringbatchPartitionConfig.class);
    context.refresh();

    final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    final Job job = (Job) context.getBean("partitionerJob");
    LOGGER.info("Starting the batch job");
    try {
        final JobExecution execution = jobLauncher.run(job, new JobParameters());
        LOGGER.info("Job Status : {}", execution.getStatus());
    } catch (final Exception e) {
        e.printStackTrace();
        LOGGER.error("Job failed {}", e.getMessage());
    }
}
 
Example #10
Source File: Panama.java    From panama with MIT License 6 votes vote down vote up
public static void load(Object ...args) {
    log.info("panama server loading");
    Class mainClass = deduceMainApplicationClass();
    List<String> basePackageList = new ArrayList<>();
    ComponentScan componentScan = (ComponentScan)mainClass.getAnnotation(ComponentScan.class);
    if (null != componentScan) {
        for (String basePackage : componentScan.basePackages()) {
            if (basePackage.length() > 0) {
                basePackageList.add(basePackage);
            }
        }
    }

    if (basePackageList.size() == 0) {
        basePackageList.add(mainClass.getPackage().getName() + ".*");
    }

    basePackageList.add(PANAMA_SPRING_SCAN_PACKAGE);
    applicationContext = new AnnotationConfigApplicationContext(basePackageList.toArray(new String[basePackageList.size()]));
    log.info("panama server loading success");
}
 
Example #11
Source File: CacheReproTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void spr14230AdaptsToOptional() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Spr14230Config.class);
	Spr14230Service bean = context.getBean(Spr14230Service.class);
	Cache cache = context.getBean(CacheManager.class).getCache("itemCache");

	TestBean tb = new TestBean("tb1");
	bean.insertItem(tb);
	assertSame(tb, bean.findById("tb1").get());
	assertSame(tb, cache.get("tb1").get());

	cache.clear();
	TestBean tb2 = bean.findById("tb1").get();
	assertNotSame(tb, tb2);
	assertSame(tb2, cache.get("tb1").get());
}
 
Example #12
Source File: AmazonRdsInstanceConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void configureBean_withDefaultClientSpecifiedAndNoReadReplicaWithExpressions_configuresFactoryBeanWithoutReadReplicaAndResolvedExpressions()
		throws Exception {
	// @checkstyle:on
	// Arrange
	this.context = new AnnotationConfigApplicationContext();
	HashMap<String, Object> propertySourceProperties = new HashMap<>();
	propertySourceProperties.put("dbInstanceIdentifier", "test");
	propertySourceProperties.put("password", "secret");
	propertySourceProperties.put("username", "admin");

	this.context.getEnvironment().getPropertySources()
			.addLast(new MapPropertySource("test", propertySourceProperties));

	// Act
	this.context
			.register(ApplicationConfigurationWithoutReadReplicaAndExpressions.class);
	this.context.refresh();

	// Assert
	assertThat(this.context.getBean(DataSource.class)).isNotNull();
	assertThat(this.context.getBean(AmazonRdsDataSourceFactoryBean.class))
			.isNotNull();
}
 
Example #13
Source File: DataFlowClientAutoConfigurationAgaintstServerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void usingUserWithAllRoles() throws Exception {

	final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
	resourceDetails.setClientId("myclient");
	resourceDetails.setClientSecret("mysecret");
	resourceDetails.setUsername("user");
	resourceDetails.setPassword("secret10");
	resourceDetails
			.setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token");

	final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
	final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();

	System.setProperty("accessTokenAsString", accessToken.getValue());

	context = new AnnotationConfigApplicationContext(TestApplication.class);

	final DataFlowOperations dataFlowOperations = context.getBean(DataFlowOperations.class);
	final AboutResource about = dataFlowOperations.aboutOperation().get();

	assertNotNull(about);
	assertEquals("user", about.getSecurityInfo().getUsername());
	assertEquals(7, about.getSecurityInfo().getRoles().size());
}
 
Example #14
Source File: CompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void overridingCompositeEnvRepo_contextLoads() {
	try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
		context.register(OverrideCompositeConfig.class, CompositeConfiguration.class,
				ConfigServerHealthIndicator.class);
		context.refresh();
	}
}
 
Example #15
Source File: ApplicationContextTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {

	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(WebConfig.class);
	context.refresh();

	this.client = WebTestClient.bindToApplicationContext(context).build();
}
 
Example #16
Source File: CrossOriginAnnotationIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ApplicationContext initApplicationContext() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(WebConfig.class);
	Properties props = new Properties();
	props.setProperty("myOrigin", "http://site1.com");
	context.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.refresh();
	return context;
}
 
Example #17
Source File: EnableCachingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void multipleCachingConfigurers() throws Throwable {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(MultiCacheManagerConfigurer.class, EnableCachingConfig.class);
	try {
		ctx.refresh();
	}
	catch (BeanCreationException ex) {
		Throwable root = ex.getRootCause();
		assertTrue(root.getMessage().contains("implementations of CachingConfigurer"));
		throw root;
	}
}
 
Example #18
Source File: InjectingResourceLoaderDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册当前类作为 Configuration Class
        context.register(InjectingResourceLoaderDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // 关闭 Spring 应用上下文
        context.close();

    }
 
Example #19
Source File: CheckCompatibilityBase.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private OasSpecDiffValidator createOasSpecDiffValidator() {
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
      DefaultOasSpecDiffValidatorFactory.class.getPackage().getName());
  try {
    OasSpecDiffValidatorFactory diffValidatorFactory = ctx.getBean(OasSpecDiffValidatorFactory.class);
    return diffValidatorFactory.create();
  } finally {
    ctx.close();
  }
}
 
Example #20
Source File: HdfsSinkPropertiesTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void fileNameCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "hdfs.fileName:mydata");
	context.register(Conf.class);
	context.refresh();
	HdfsSinkProperties properties = context.getBean(HdfsSinkProperties.class);
	assertThat(properties.getFileName(), equalTo("mydata"));
}
 
Example #21
Source File: EnableTransactionManagementTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void spr14322FindsOnInterfaceWithCglibProxy() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14322ConfigB.class);
	TransactionalTestInterface bean = ctx.getBean(TransactionalTestInterface.class);
	CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class);

	bean.saveFoo();
	bean.saveBar();
	assertThat(txManager.begun, equalTo(2));
	assertThat(txManager.commits, equalTo(2));
	assertThat(txManager.rollbacks, equalTo(0));

	ctx.close();
}
 
Example #22
Source File: ProxyAnnotationDiscoveryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void nonAnnotatedService_PTC_true() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(PTCTrue.class, AnnotatedServiceImpl.class);
	ctx.refresh();
	NonAnnotatedService s = ctx.getBean(NonAnnotatedService.class);
	assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s));
	assertThat(s, instanceOf(AnnotatedServiceImpl.class));
}
 
Example #23
Source File: MetricDescriptorValidatorTool.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CommandLine cmdLine, OutputStream out, OutputStream err)
    throws Exception {
  Preconditions.checkNotNull(cmdLine);
  Preconditions.checkNotNull(out);
  Preconditions.checkNotNull(err);

  Writer writer = new OutputStreamWriter(out, "UTF-8");
  try {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(
        DefaultValidatorConfiguration.class);
    @SuppressWarnings("unchecked")
    Parser<ServiceMonitoringDefinitionsDescriptor> parser =
      ctx.getBean("mdlParser", Parser.class);
    @SuppressWarnings("unchecked")
    DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> validator =
      ctx.getBean("serviceMonitoringDefinitionsDescriptorValidator",
                  DescriptorValidator.class);
    ValidationRunner runner =
        new DescriptorRunner<ServiceMonitoringDefinitionsDescriptor>(
            parser, validator);
    if (!runner.run(cmdLine.getOptionValue(OPT_MDL.getLongOpt()), writer)) {
      throw new RuntimeException("Validation failed.");
    }
  } catch (Exception ex) {
    LOG.error("Could not run validation tool.", ex);
    IOUtils.write(ex.getMessage() + "\n", err);
    throw ex;
  } finally {
    writer.close();
  }
}
 
Example #24
Source File: SurveyHarness.java    From waltz with Apache License 2.0 5 votes vote down vote up
private static void surveyTempateHarness(AnnotationConfigApplicationContext ctx) {
    SurveyTemplateService surveyTemplateService = ctx.getBean(SurveyTemplateService.class);
    SurveyQuestionService surveyQuestionService = ctx.getBean(SurveyQuestionService.class);

    SurveyTemplateChangeCommand surveyTemplateChangeCommand = ImmutableSurveyTemplateChangeCommand.builder()
            .name("AAA")
            .description("BBB")
            .targetEntityKind(EntityKind.CHANGE_INITIATIVE)
            .build();

    long templateId = surveyTemplateService.create("admin", surveyTemplateChangeCommand);
    System.out.println("Created: template create with ID = " + templateId);

    SurveyQuestion surveyQuestion = ImmutableSurveyQuestion.builder()
            .surveyTemplateId(templateId)
            .sectionName("SSS")
            .questionText("QQQ")
            .helpText("HHH")
            .fieldType(SurveyQuestionFieldType.TEXTAREA)
            .position(1)
            .isMandatory(false)
            .allowComment(true)
            .build();

    long questionId = surveyQuestionService.create(surveyQuestion);
    System.out.println("Created: question create with ID = " + questionId);
}
 
Example #25
Source File: ContentMongoAutoConfigurationTest.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(TestConfig.class);
	context.refresh();

	MatcherAssert.assertThat(context.getBean(TestEntityContentRepository.class),
			CoreMatchers.is(CoreMatchers.not(CoreMatchers.nullValue())));

	context.close();
}
 
Example #26
Source File: HttpInvokerFactoryBeanIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void withConfigurationClassWithPlainFactoryBean() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(ConfigWithPlainFactoryBean.class);
	context.refresh();
	MyBean myBean = context.getBean("myBean", MyBean.class);
	assertSame(context.getBean("myService"), myBean.myService);
	myBean.myService.handle();
	myBean.myService.handleAsync();
}
 
Example #27
Source File: SolaceJmsAutoConfigurationTestBase.java    From solace-jms-spring-boot with Apache License 2.0 5 votes vote down vote up
void load(Class<?> config, String... environment) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    TestPropertyValues.of(environment).applyTo(applicationContext);
    applicationContext.register(config);
    applicationContext.register(configClass, JmsAutoConfiguration.class);
    applicationContext.refresh();
    this.context = applicationContext;
}
 
Example #28
Source File: EnableCachingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void multipleCachingConfigurers() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(MultiCacheManagerConfigurer.class, EnableCachingConfig.class);
	try {
		ctx.refresh();
	}
	catch (BeanCreationException ex) {
		Throwable root = ex.getRootCause();
		assertTrue(root instanceof IllegalStateException);
		assertTrue(root.getMessage().contains("implementations of CachingConfigurer"));
	}
}
 
Example #29
Source File: DIFactory.java    From di-benchmark with MIT License 5 votes vote down vote up
public static ApplicationContext spring(boolean scan) {
    if (scan) {
        return new AnnotationConfigApplicationContext("com.greenlaw110.di_benchmark.objects");
    } else {
        return new AnnotationConfigApplicationContext(SpringConfig.class);
    }
}
 
Example #30
Source File: DefaultRiptideConfigurerTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldFindBeanDefinitionByNameIfNoPrimaryBeanAvailable() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(DoubleTracerConfiguration.class);
    context.refresh();
    final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    final DefaultRiptideConfigurer configurer = new DefaultRiptideConfigurer(beanFactory, null);
    final BeanReference bd = configurer.getBeanRef(Tracer.class, "tracer");
    assertThat(bd.getBeanName()).isEqualTo("tracer");
}