Java Code Examples for org.springframework.context.annotation.AnnotationConfigApplicationContext

The following examples show how to use org.springframework.context.annotation.AnnotationConfigApplicationContext. These examples are extracted from open source projects. 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 Project: waltz   Source File: SoftwareCatalogHarness.java    License: 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
@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
@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
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 Project: waltz   Source File: UnionHarness.java    License: 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
@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
@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 Project: apollo   Source File: JavaConfigPlaceholderTest.java    License: 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 Project: tutorials   Source File: SpringbatchPartitionerApp.java    License: 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 Project: panama   Source File: Panama.java    License: 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 Project: java-technology-stack   Source File: CacheReproTests.java    License: 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
@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
@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
@Test
public void overridingCompositeEnvRepo_contextLoads() {
	try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
		context.register(OverrideCompositeConfig.class, CompositeConfiguration.class,
				ConfigServerHealthIndicator.class);
		context.refresh();
	}
}
 
Example 15
Source Project: java-technology-stack   Source File: ApplicationContextTests.java    License: 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
@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 Project: spring4-understanding   Source File: EnableCachingTests.java    License: 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
public static void main(String[] args) {

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

    }
 
Example 19
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
@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
@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
@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 Project: cm_ext   Source File: MetricDescriptorValidatorTool.java    License: 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 Project: waltz   Source File: SurveyHarness.java    License: 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
@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
@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
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 Project: spring-analysis-note   Source File: EnableCachingTests.java    License: 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 Project: di-benchmark   Source File: DIFactory.java    License: 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 Project: riptide   Source File: DefaultRiptideConfigurerTest.java    License: 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");
}