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 |
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: RSocketClientToServerIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #3
Source File: UnionHarness.java From waltz with Apache License 2.0 | 6 votes |
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 #4
Source File: OnceApplicationContextEventListenerTest.java From spring-context-support with Apache License 2.0 | 6 votes |
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: Panama.java From panama with MIT License | 6 votes |
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 #6
Source File: SpringbatchPartitionerApp.java From tutorials with MIT License | 6 votes |
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 #7
Source File: JavaConfigPlaceholderTest.java From apollo with Apache License 2.0 | 6 votes |
@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 #8
Source File: ConfigurationBeanNameTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #9
Source File: CacheReproTests.java From java-technology-stack with MIT License | 6 votes |
@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 #10
Source File: ContextResourceLoaderAutoConfigurationTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@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 #11
Source File: FeignClientFactoryTests.java From spring-cloud-openfeign with Apache License 2.0 | 6 votes |
@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 #12
Source File: AmazonRdsInstanceConfigurationTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@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 |
@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: EnableSchedulingTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void withTriggerTask() throws InterruptedException { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(TriggerTaskConfig.class); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThan(1)); }
Example #15
Source File: EnableTransactionManagementTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void transactionProxyIsCreatedWithEnableOnExcludedSuperclass() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( ParentEnableTxConfig.class, ChildEnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); ctx.close(); }
Example #16
Source File: EnableJmsTests.java From spring-analysis-note with MIT License | 5 votes |
@Override @Test public void fullConfiguration() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableJmsFullConfig.class, FullBean.class); testFullConfiguration(context); }
Example #17
Source File: MethodValidationTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testLazyValidatorForMethodValidationWithProxyTargetClass() { @SuppressWarnings("resource") AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( LazyMethodValidationConfigWithProxyTargetClass.class, CustomValidatorBean.class, MyValidBean.class, MyValidFactoryBean.class); ctx.getBeansOfType(MyValidInterface.class).values().forEach(bean -> bean.myValidMethod("value", 5)); }
Example #18
Source File: EnableTransactionManagementTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void transactionProxyIsCreated() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( EnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map<?,?> services = ctx.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); ctx.close(); }
Example #19
Source File: JythonScriptTemplateTests.java From java-technology-stack with MIT License | 5 votes |
private ScriptTemplateView createViewWithUrl(String viewUrl) throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ScriptTemplatingConfiguration.class); ctx.refresh(); ScriptTemplateView view = new ScriptTemplateView(); view.setApplicationContext(ctx); view.setUrl(viewUrl); view.afterPropertiesSet(); return view; }
Example #20
Source File: EnableSchedulingTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void withTriggerTask() throws InterruptedException { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(TriggerTaskConfig.class); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThan(1)); }
Example #21
Source File: SpringContainer.java From ace with Apache License 2.0 | 5 votes |
@Override public void init(String... packages) { applicationContext = new AnnotationConfigApplicationContext(); Config config= DefaultConfig.INSTANCE; ConfigBeanFactoryPostProcessor configBeanFactoryPostProcessor = new ConfigBeanFactoryPostProcessor(config); applicationContext.addBeanFactoryPostProcessor(configBeanFactoryPostProcessor); applicationContext.scan(packages); }
Example #22
Source File: BootstrapTest.java From Spring with Apache License 2.0 | 5 votes |
/** * Bootstrap Configuration class using context class */ @Test public void testStart3() { ApplicationContext ctx = new AnnotationConfigApplicationContext(UserRepoDSConfig.class); DataSource dataSource = ctx.getBean("dataSource", DataSource.class); assertNotNull(dataSource); UserRepo userRepo = ctx.getBean("userRepo", UserRepo.class); assertNotNull(userRepo); }
Example #23
Source File: FeignClientValidationTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void validLoadBalanced() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( LoadBalancerAutoConfiguration.class, org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration.class, FeignLoadBalancerAutoConfiguration.class, GoodServiceIdConfiguration.class); assertThat(context.getBean(GoodServiceIdConfiguration.Client.class)).isNotNull(); context.close(); }
Example #24
Source File: QuickFixJClientAutoConfigurationTest.java From quickfixj-spring-boot-starter with Apache License 2.0 | 5 votes |
@Test public void testAutoConfiguredBeansSingleThreadedInitiator() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SingleThreadedClientInitiatorConfiguration.class); ConnectorManager clientConnectionManager = ctx.getBean("clientConnectionManager", ConnectorManager.class); assertThat(clientConnectionManager.isRunning()).isFalse(); assertThat(clientConnectionManager.isAutoStartup()).isFalse(); Initiator clientInitiator = ctx.getBean(Initiator.class); assertThat(clientInitiator).isInstanceOf(SocketInitiator.class); hasAutoConfiguredBeans(ctx); }
Example #25
Source File: JCacheJavaConfigTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void fullCachingConfig() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FullCachingConfig.class); DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); assertSame(context.getBean(KeyGenerator.class), cos.getKeyGenerator()); assertSame(context.getBean("cacheResolver", CacheResolver.class), cos.getCacheResolver()); assertSame(context.getBean("exceptionCacheResolver", CacheResolver.class), cos.getExceptionCacheResolver()); JCacheInterceptor interceptor = context.getBean(JCacheInterceptor.class); assertSame(context.getBean("errorHandler", CacheErrorHandler.class), interceptor.getErrorHandler()); }
Example #26
Source File: EnableTransactionManagementTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void spr14322FindsOnInterfaceWithInterfaceProxy() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14322ConfigA.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 #27
Source File: HdfsSinkPropertiesTests.java From spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
@Test public void directoryCanBeCustomized() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(context, "hdfs.directory:/tmp/test"); context.register(Conf.class); context.refresh(); HdfsSinkProperties properties = context.getBean(HdfsSinkProperties.class); assertThat(properties.getDirectory(), equalTo("/tmp/test")); }
Example #28
Source File: AmazonConfigurationTest.java From service-block-samples with Apache License 2.0 | 5 votes |
private void load(Class<?> config, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.register(config); applicationContext.register(AmazonAutoConfiguration.class); applicationContext.refresh(); this.context = applicationContext; }
Example #29
Source File: ConfigurationBeanNameTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void registerOuterConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(A.class); ctx.refresh(); assertThat(ctx.containsBean("outer"), is(true)); assertThat(ctx.containsBean("imported"), is(true)); assertThat(ctx.containsBean("nested"), is(true)); assertThat(ctx.containsBean("nestedBean"), is(true)); }
Example #30
Source File: AmazonS3SinkPropertiesTests.java From spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
@Test public void aclAndAclExpressionAreMutuallyExclusive() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(context, "s3.bucket:foo", "s3.acl:private", "s3.acl-expression:'acl'"); context.register(Conf.class); try { context.refresh(); fail("BeanCreationException expected"); } catch (Exception e) { assertThat(e, instanceOf(BeanCreationException.class)); assertThat(e.getMessage(), containsString("Only one of 'acl' or 'aclExpression' must be set")); } }