下面列出了org.springframework.context.annotation.AnnotationConfigApplicationContext#getBean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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));
}
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();
}
@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 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
}
@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"));
}
@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();
}
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());
}
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);
}
@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();
}
@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")));
}
@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));
}
@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"));
}
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();
}
@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;
}
@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());
}
@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();
}
@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");
}
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);
}
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());
}
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();
}