Java Code Examples for org.springframework.context.annotation.AnnotationConfigApplicationContext#getBean()

The following examples show how to use org.springframework.context.annotation.AnnotationConfigApplicationContext#getBean() . 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: EnableTransactionManagementIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void explicitTxManager() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ExplicitTxManagerConfig.class);
	ctx.refresh();

	FooRepository fooRepository = ctx.getBean(FooRepository.class);
	fooRepository.findAll();

	CallCountingTransactionManager txManager1 = ctx.getBean("txManager1", CallCountingTransactionManager.class);
	assertThat(txManager1.begun, equalTo(1));
	assertThat(txManager1.commits, equalTo(1));
	assertThat(txManager1.rollbacks, equalTo(0));

	CallCountingTransactionManager txManager2 = ctx.getBean("txManager2", CallCountingTransactionManager.class);
	assertThat(txManager2.begun, equalTo(0));
	assertThat(txManager2.commits, equalTo(0));
	assertThat(txManager2.rollbacks, equalTo(0));
}
 
Example 2
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 3
Source File: NoUniqueBeanDefinitionExceptionDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 创建 BeanFactory 容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    // 将当前类 NoUniqueBeanDefinitionExceptionDemo 作为配置类(Configuration Class)
    applicationContext.register(NoUniqueBeanDefinitionExceptionDemo.class);
    // 启动应用上下文
    applicationContext.refresh();

    try {
        // 由于 Spring 应用上下文存在两个 String 类型的 Bean,通过单一类型查找会抛出异常
        applicationContext.getBean(String.class);
    } catch (NoUniqueBeanDefinitionException e) {
        System.err.printf(" Spring 应用上下文存在%d个 %s 类型的 Bean,具体原因:%s%n",
                e.getNumberOfBeansFound(),
                String.class.getName(),
                e.getMessage());
    }

    // 关闭应用上下文
    applicationContext.close();
}
 
Example 4
Source File: AmazonS3SinkPropertiesTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void s3BucketExpressionCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "s3.bucket-expression:headers.bucket");
	context.register(Conf.class);
	context.refresh();
	AmazonS3SinkProperties properties = context.getBean(AmazonS3SinkProperties.class);
	assertThat(properties.getBucketExpression().getExpressionString(), equalTo("headers.bucket"));
	context.close();
}
 
Example 5
Source File: FtpSourcePropertiesTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteRemoteFilesCanBeEnabled() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "ftp.deleteRemoteFiles:true");
	context.register(Conf.class);
	context.refresh();
	FtpSourceProperties properties = context.getBean(FtpSourceProperties.class);
	assertTrue(properties.isDeleteRemoteFiles());
}
 
Example 6
Source File: JCacheEhCacheAnnotationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected ConfigurableApplicationContext getApplicationContext() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.getBeanFactory().registerSingleton("cachingProvider", getCachingProvider());
	context.register(EnableCachingConfig.class);
	context.refresh();
	jCacheManager = context.getBean("jCacheManager", CacheManager.class);
	return context;
}
 
Example 7
Source File: SpringMainClass.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) throws SQLException {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.scan("com.journaldev.spring");
	context.refresh();

	EmployeeRepository repository = context.getBean(EmployeeRepository.class);

	// store
	repository.store(new Employee(1, "Pankaj", "CEO"));
	repository.store(new Employee(2, "Anupam", "Editor"));
	repository.store(new Employee(3, "Meghna", "CFO"));

	// retrieve
	Employee emp = repository.retrieve(1);
	System.out.println(emp);

	// search
	Employee cfo = repository.search("Meghna");
	System.out.println(cfo);

	// delete
	Employee editor = repository.delete(2);
	System.out.println(editor);

	// close the spring context
	context.close();
}
 
Example 8
Source File: BeanMethodQualificationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testScoped() {
	AnnotationConfigApplicationContext ctx =
			new AnnotationConfigApplicationContext(ScopedConfig.class, StandardPojo.class);
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
	StandardPojo pojo = ctx.getBean(StandardPojo.class);
	assertThat(pojo.testBean.getName(), equalTo("interesting"));
	assertThat(pojo.testBean2.getName(), equalTo("boring"));
}
 
Example 9
Source File: KinesisAutoConfigurationTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterRetryPolicyWithMaxRetries() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(KinesisAutoConfiguration.class);
    context.refresh();

    assertThat(context.containsBean("kinesisRetryPolicy"), is(true));
    RetryPolicy retryPolicy = context.getBean("kinesisRetryPolicy", RetryPolicy.class);
    assertThat(retryPolicy.numRetries(), is(Integer.MAX_VALUE));
}
 
Example 10
Source File: ImageRecognitionProcessorPropertiesTests.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
@Test
public void labelsCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	TestPropertyValues.of("tensorflow.image.recognition.labels:/remote").applyTo(context);
	context.register(Conf.class);
	context.refresh();
	ImageRecognitionProcessorProperties properties = context.getBean(ImageRecognitionProcessorProperties.class);
	assertThat(properties.getLabels(), equalTo(context.getResource("/remote")));
}
 
Example 11
Source File: EnableAsyncTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void orderAttributeIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(OrderedAsyncConfig.class);
	ctx.refresh();

	AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class);
	assertThat(bpp.getOrder(), is(Ordered.HIGHEST_PRECEDENCE));

	ctx.close();
}
 
Example 12
Source File: MetadataLocalAnnotationConsumer.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
    context.start();

    printServiceData();

    AnnotationAction annotationAction = context.getBean("annotationAction", AnnotationAction.class);
    String hello = annotationAction.doSayHello("world");
    System.out.println("result :" + hello);
}
 
Example 13
Source File: DataExtractHarness.java    From waltz with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ParseException {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
        DSLContext dsl = ctx.getBean(DSLContext.class);
        LogicalFlowIdSelectorFactory logicalFlowIdSelectorFactory = new LogicalFlowIdSelectorFactory();

        IdSelectionOptions options = IdSelectionOptions.mkOpts(
                EntityReference.mkRef(EntityKind.ORG_UNIT, 4326),
                HierarchyQueryScope.CHILDREN);

        Select<Record1<Long>> flowIdSelector = logicalFlowIdSelectorFactory.apply(options);

        Application sourceApp = APPLICATION.as("sourceApp");
        Application targetApp = APPLICATION.as("targetApp");
        OrganisationalUnit sourceOrgUnit = ORGANISATIONAL_UNIT.as("sourceOrgUnit");
        OrganisationalUnit targetOrgUnit = ORGANISATIONAL_UNIT.as("targetOrgUnit");

        Result<Record> fetch = dsl.select(LOGICAL_FLOW.fields())
                .select(SOURCE_NAME_FIELD, TARGET_NAME_FIELD)
                .select(sourceApp.fields())
                .select(targetApp.fields())
                .select(sourceOrgUnit.fields())
                .select(targetOrgUnit.fields())
                .select(LOGICAL_FLOW_DECORATOR.fields())
                .from(LOGICAL_FLOW)
                .leftJoin(sourceApp).on(LOGICAL_FLOW.SOURCE_ENTITY_ID.eq(sourceApp.ID).and(LOGICAL_FLOW.SOURCE_ENTITY_KIND.eq(EntityKind.APPLICATION.name())))
                .leftJoin(targetApp).on(LOGICAL_FLOW.TARGET_ENTITY_ID.eq(targetApp.ID).and(LOGICAL_FLOW.TARGET_ENTITY_KIND.eq(EntityKind.APPLICATION.name())))
                .leftJoin(sourceOrgUnit).on(sourceApp.ORGANISATIONAL_UNIT_ID.eq(sourceOrgUnit.ID))
                .leftJoin(targetOrgUnit).on(targetApp.ORGANISATIONAL_UNIT_ID.eq(targetOrgUnit.ID))
                .join(LOGICAL_FLOW_DECORATOR).on(LOGICAL_FLOW_DECORATOR.LOGICAL_FLOW_ID.eq(LOGICAL_FLOW.ID).and(LOGICAL_FLOW_DECORATOR.DECORATOR_ENTITY_KIND.eq("DATA_TYPE")))
                .where(LOGICAL_FLOW.ID.in(flowIdSelector))
                .and(LOGICAL_FLOW.ENTITY_LIFECYCLE_STATUS.ne(REMOVED.name()))
                .fetch();

        System.out.printf("got records: %s", fetch.size());

    }
 
Example 14
Source File: AmazonS3SinkPropertiesTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void aclExpressionCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "s3.bucket:foo", "S3_ACL_EXPRESSION:headers.acl");
	context.register(Conf.class);
	context.refresh();
	AmazonS3SinkProperties properties = context.getBean(AmazonS3SinkProperties.class);
	assertThat(properties.getAclExpression().getExpressionString(), equalTo("headers.acl"));
	context.close();
}
 
Example 15
Source File: SparkClientTaskPropertiesTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppNameCanBeCustomized() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(context, "spark.app-class: Dummy");
    EnvironmentTestUtils.addEnvironment(context, "spark.app-jar: dummy.jar");
    EnvironmentTestUtils.addEnvironment(context, "spark.app-name: test");
    context.register(Conf.class);
    context.refresh();
    SparkClientTaskProperties properties = context.getBean(SparkClientTaskProperties.class);
    assertThat(properties.getAppName(), equalTo("test"));
}
 
Example 16
Source File: PackagePrivateBeanMethodInheritanceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void repro() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ReproConfig.class);
	ctx.refresh();
	Foo foo1 = ctx.getBean("foo1", Foo.class);
	Foo foo2 = ctx.getBean("foo2", Foo.class);
	ctx.getBean("packagePrivateBar", Bar.class); // <-- i.e. @Bean was registered
	assertThat(foo1.bar, not(is(foo2.bar)));     // <-- i.e. @Bean *not* enhanced
}
 
Example 17
Source File: QuickFixJClientAutoConfigurationTest.java    From quickfixj-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Test
public void testAutoConfiguredBeansSingleThreadedInitiatorWithCustomClientSettings() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SingleThreadedClientInitiatorConfigurationWithCustomClientSettings.class);
	SessionSettings customClientSessionSettings = ctx.getBean("clientSessionSettings", SessionSettings.class);
	assertThat(customClientSessionSettings.getDefaultProperties().getProperty("SenderCompID")).isEqualTo("CUSTOM-BANZAI");
}
 
Example 18
Source File: JobLogHarness.java    From waltz with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws ParseException {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);

        JobLogDao jobLogDao = ctx.getBean(JobLogDao.class);

        jobLogDao.findLatestSuccessful()
                .forEach(System.out::println);

    }
 
Example 19
Source File: EndUserAppHarness.java    From waltz with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws ParseException {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
        EndUserAppDao dao = ctx.getBean(EndUserAppDao.class);

        
        System.out.println(dao.countByOrganisationalUnit());

    }
 
Example 20
Source File: Main.java    From spring4.x-project with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {
	 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
	 
	 DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
	 
	 demoPublisher.publish("hello application event");
	 
	 context.close();
}