类org.springframework.context.annotation.AnnotationConfigApplicationContext源码实例Demo

下面列出了怎么用org.springframework.context.annotation.AnnotationConfigApplicationContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: waltz   文件: SoftwareCatalogHarness.java
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);
}
 
@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();
}
 
@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));
}
 
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;
    }
 
源代码5 项目: waltz   文件: UnionHarness.java
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);
}
 
@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();
}
 
@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();
}
 
源代码8 项目: apollo   文件: JavaConfigPlaceholderTest.java
@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());
}
 
源代码9 项目: tutorials   文件: SpringbatchPartitionerApp.java
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());
    }
}
 
源代码10 项目: panama   文件: Panama.java
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");
}
 
源代码11 项目: java-technology-stack   文件: CacheReproTests.java
@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());
}
 
@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();
}
 
@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());
}
 
@Test
public void overridingCompositeEnvRepo_contextLoads() {
	try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
		context.register(OverrideCompositeConfig.class, CompositeConfiguration.class,
				ConfigServerHealthIndicator.class);
		context.refresh();
	}
}
 
@Before
public void setUp() throws Exception {

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

	this.client = WebTestClient.bindToApplicationContext(context).build();
}
 
@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;
}
 
源代码17 项目: spring4-understanding   文件: EnableCachingTests.java
@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;
	}
}
 
public static void main(String[] args) {

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

    }
 
private OasSpecDiffValidator createOasSpecDiffValidator() {
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
      DefaultOasSpecDiffValidatorFactory.class.getPackage().getName());
  try {
    OasSpecDiffValidatorFactory diffValidatorFactory = ctx.getBean(OasSpecDiffValidatorFactory.class);
    return diffValidatorFactory.create();
  } finally {
    ctx.close();
  }
}
 
@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"));
}
 
@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();
}
 
@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));
}
 
源代码23 项目: cm_ext   文件: MetricDescriptorValidatorTool.java
@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();
  }
}
 
源代码24 项目: waltz   文件: SurveyHarness.java
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);
}
 
@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();
}
 
@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();
}
 
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;
}
 
源代码28 项目: spring-analysis-note   文件: EnableCachingTests.java
@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"));
	}
}
 
源代码29 项目: di-benchmark   文件: DIFactory.java
public static ApplicationContext spring(boolean scan) {
    if (scan) {
        return new AnnotationConfigApplicationContext("com.greenlaw110.di_benchmark.objects");
    } else {
        return new AnnotationConfigApplicationContext(SpringConfig.class);
    }
}
 
源代码30 项目: riptide   文件: DefaultRiptideConfigurerTest.java
@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");
}
 
 同包方法