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

The following are top voted examples for showing how to use org.springframework.context.annotation.AnnotationConfigApplicationContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: zipkin-collector-eventhub   File: EventHubCollectorAutoConfigurationTest.java   Source Code and License 7 votes vote down vote up
@Test
public void provideCollectorComponent_canSetStorageContainerName() {

    String storageContainerName = "pashmak";

    context = new AnnotationConfigApplicationContext();
    addEnvironment(context, "zipkin.collector.eventhub.storageConnectionString:" + dummyEventHubConnectionString);
    addEnvironment(context, "zipkin.collector.eventhub.eventHubConnectionString:" + dummyStorageConnectionString );
    addEnvironment(context, "zipkin.collector.eventhub.storageContainerName:" + storageContainerName);
    context.register(PropertyPlaceholderAutoConfiguration.class,
            EventHubCollectorAutoConfiguration.class,
            InMemoryConfiguration.class);
    context.refresh();

    EventHubCollector collector = context.getBean(EventHubCollector.class);
    assertNotNull(collector);
    assertEquals(storageContainerName, collector.getStorageContainerName());
}
 
Example 2
Project: sponge   File: SimpleCamelProducerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCamelProducer() throws Exception {
    // Starting Spring context.
    try (GenericApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfiguration.class)) {
        context.start();

        // Sending Camel message.
        CamelContext camel = context.getBean(CamelContext.class);
        ProducerTemplate producerTemplate = camel.createProducerTemplate();
        producerTemplate.sendBody("direct:start", "Send me to the Sponge");

        // Waiting for the engine to process an event.
        Engine engine = context.getBean(Engine.class);
        await().atMost(60, TimeUnit.SECONDS)
                .until(() -> engine.getOperations().getVariable(AtomicBoolean.class, "sentCamelMessage").get());

        assertFalse(engine.isError());
        context.stop();
    }
}
 
Example 3
Project: easypump   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main (String [] args)
{
	@SuppressWarnings({ "resource"})
	AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
	
	PumpEngine engine = (PumpEngine)context.getBean(PumpEngine.class);
	engine.setArgs(args);
	try {
		engine.startPump();
	} catch (Exception e) {			
		logger.error("Exception Occured while doing buy/sell transaction", e);			
	}		
	
	System.out.println("\n\n\nHope you will make a profit in this pump ;)");
	System.out.println("if you could make a proit using this app please conside doing some donation with 1$ or 2$ to BTC address 1PfnwEdmU3Ki9htakiv4tciPXzo49RRkai \nit will help us doing more features in the future");
}
 
Example 4
Project: wecard-server   File: NServer.java   Source Code and License 6 votes vote down vote up
public void init() {
    //启动并设置Spring
    AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    ctx.registerShutdownHook();
    NContext.setApplicationContext(ctx);

    //初始化房间管理器
    HomeManager homeManager = HomeManager.getInstance();
    homeManager.init();

    //初始化用户管理器
    PlayerManager playerManager = PlayerManager.getInstance();
    playerManager.init();

    //初始化Gateway
    ClientManager clientManager = ClientManager.getInstance();
    clientManager.init();

    //启动异步处理器
    AsyncProcessor asyncProcessor = AsyncProcessor.getInstance();
    asyncProcessor.start();

    //启动滴答服务
    TickerService tickerService = TickerService.getInstance();
    tickerService.start();
}
 
Example 5
Project: azure-spring-boot   File: MediaServicesAutoConfigurationTest.java   Source Code and License 6 votes vote down vote up
private void createAndFailWithCause(String cause) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(MediaServicesAutoConfiguration.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getCause().toString()).contains(cause);
    }
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: TestLastPropertyPlaceholderConfigurer.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
  AnnotationConfigApplicationContext context =
      new AnnotationConfigApplicationContext(this.getClass().getPackage().getName());
  Bean bean = context.getBean(Bean.class);

  Assert.assertEquals("aValue", bean.resolver.resolveStringValue("${a}"));
  try {
    bean.resolver.resolveStringValue("${b}");
    Assert.fail("must throw exception");
  } catch (IllegalArgumentException e) {
    Assert.assertEquals("Could not resolve placeholder 'b' in string value \"${b}\"", e.getMessage());
  }

  context.close();
}
 
Example 7
Project: Spring-5.0-Cookbook   File: TestScopes.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	   context.register(BeanConfig.class);
   
	   System.out.println("application context loaded.");
        
       context.refresh();
       System.out.println("*********The empRec1 bean ***************");
       Employee empRec1A = (Employee) context.getBean("empRec1");
       System.out.println("instance A: " + empRec1A.hashCode());
       Employee empRec1B = (Employee) context.getBean("empRec1");
       System.out.println("instance B: " +empRec1B.hashCode());
       
       System.out.println("*********The empRec2 bean ***************");
       Employee empRec2A = (Employee) context.getBean("empRec2");
       System.out.println("instance A: " + empRec2A.hashCode());
       Employee empRec2B = (Employee) context.getBean("empRec2");
       System.out.println("instance B: " + empRec2B.hashCode());
       
       context.registerShutdownHook();
}
 
Example 8
Project: zipkin-collector-eventhub   File: EventHubCollectorAutoConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void provideCollectorComponent_canSetCheckpointBatchSize() {

    int checkpointBatchSize = 1000;

    context = new AnnotationConfigApplicationContext();
    addEnvironment(context, "zipkin.collector.eventhub.storageConnectionString:" + dummyEventHubConnectionString);
    addEnvironment(context, "zipkin.collector.eventhub.eventHubConnectionString:" + dummyStorageConnectionString );
    addEnvironment(context, "zipkin.collector.eventhub.checkpoint-batch-size:" + checkpointBatchSize);
    context.register(PropertyPlaceholderAutoConfiguration.class,
            EventHubCollectorAutoConfiguration.class,
            InMemoryConfiguration.class);
    context.refresh();

    EventHubCollector collector = context.getBean(EventHubCollector.class);
    assertNotNull(collector);
    assertEquals(checkpointBatchSize, collector.getCheckpointBatchSize());
}
 
Example 9
Project: spring-session-data-mongodb   File: ReactiveMongoWebSessionConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void enableSpringWebSessionConfiguresThings() {

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(GoodConfig.class);
	this.context.refresh();

	WebSessionManager webSessionManagerFoundByType = this.context.getBean(WebSessionManager.class);
	Object webSessionManagerFoundByName = this.context.getBean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME);

	assertThat(webSessionManagerFoundByType).isNotNull();
	assertThat(webSessionManagerFoundByName).isNotNull();
	assertThat(webSessionManagerFoundByType).isEqualTo(webSessionManagerFoundByName);

	assertThat(this.context.getBean(ReactiveSessionRepository.class)).isNotNull();
}
 
Example 10
Project: dev-courses   File: Main2.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
	IToDoListDAO repository = context.getBean(IToDoListDAO.class);
	
       // fetch all ToDoLists
       System.out.println("ToDoLists found with findAll():");
       System.out.println("-------------------------------");
       for (ToDoList ToDoList : repository.findAll()) {
           System.out.println(ToDoList);
       }
       System.out.println();
	
	context.close();

}
 
Example 11
Project: azure-spring-boot   File: StorageAutoConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createStorageAccountWithInvalidConnectionString() {
    System.setProperty(CONNECTION_STRING_PROPERTY, INVALID_CONNECTION_STRING);

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(StorageAutoConfiguration.class);
        context.refresh();

        CloudStorageAccount cloudStorageAccount = null;
        try {
            cloudStorageAccount = context.getBean(CloudStorageAccount.class);
        } catch (Exception e) {
            assertThat(e).isExactlyInstanceOf(BeanCreationException.class);
        }

        assertThat(cloudStorageAccount).isNull();
    }

    System.clearProperty(CONNECTION_STRING_PROPERTY);
}
 
Example 12
Project: azure-spring-boot   File: ServiceBusAutoConfigurationTest.java   Source Code and License 6 votes vote down vote up
private void verifyBeanCreationException(String message, Class<?> beanClass) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        Exception exception = null;
        try {
            context.register(ServiceBusAutoConfiguration.class);
            context.refresh();
            context.getBean(beanClass);
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception.getMessage()).contains(message);
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
    }
}
 
Example 13
Project: azure-spring-boot   File: DocumentDBPropertiesTest.java   Source Code and License 6 votes vote down vote up
@Test
public void canSetAllProperties() {
    PropertySettingUtil.setProperties();

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);
        context.refresh();
        final DocumentDBProperties properties = context.getBean(DocumentDBProperties.class);

        assertThat(properties.getUri()).isEqualTo(PropertySettingUtil.URI);
        assertThat(properties.getKey()).isEqualTo(PropertySettingUtil.KEY);
        assertThat(properties.getConsistencyLevel()).isEqualTo(PropertySettingUtil.CONSISTENCY_LEVEL);
        assertThat(properties.isAllowTelemetry()).isEqualTo(PropertySettingUtil.ALLOW_TELEMETRY_TRUE);
    }

    PropertySettingUtil.unsetProperties();
}
 
Example 14
Project: redirector   File: WebServiceClientHelper.java   Source Code and License 6 votes vote down vote up
public static HttpServer httpBuilder (String connectionUrl) {
    try {
        URL url = new URL(connectionUrl);

        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringAnnotationConfig.class);

        ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.register(RequestContextFilter.class);
        resourceConfig.property("contextConfig", annotationConfigApplicationContext);
        resourceConfig.register(RestSupport.class);

        URI baseUri = URI.create(url.getProtocol() + "://" + url.getAuthority());
        return  GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, false);
    } catch (Exception e) {
        Assert.fail("Could'n parse configfile." + e.getMessage());
    }
    return null;
}
 
Example 15
Project: db-queue   File: SpringQueueCollectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_fail_on_invalid_queue_definitions() throws Exception {
    try {
        new AnnotationConfigApplicationContext(InvalidContext.class);
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), equalTo("unable to collect queue beans:" + System.lineSeparator() +
                "duplicate bean: name=testProducer2, class=SpringQueueProducer, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=testConsumer2, class=SpringQueueConsumer, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=testTransformer2, class=SpringTaskPayloadTransformer, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=testShardRouter2, class=SpringQueueShardRouter, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=springTaskLifecycleListener2, class=SpringTaskLifecycleListener, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=springThreadLifecycleListener2, class=SpringThreadLifecycleListener, queueId=test_queue" + System.lineSeparator() +
                "duplicate bean: name=springQueueExternalExecutor2, class=SpringQueueExternalExecutor, queueId=test_queue"));
        return;
    }
    Assert.fail("context should not be constructed");
}
 
Example 16
Project: zipkin-collector-eventhub   File: EventHubCollectorAutoConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void provideCollectorComponent_canSetProcessorHostName() {

    String processorHostName = "pashmak";

    context = new AnnotationConfigApplicationContext();
    addEnvironment(context, "zipkin.collector.eventhub.storageConnectionString:" + dummyEventHubConnectionString);
    addEnvironment(context, "zipkin.collector.eventhub.eventHubConnectionString:" + dummyStorageConnectionString );
    addEnvironment(context, "zipkin.collector.eventhub.processorHostName:" + processorHostName);
    context.register(PropertyPlaceholderAutoConfiguration.class,
            EventHubCollectorAutoConfiguration.class,
            InMemoryConfiguration.class);
    context.refresh();

    EventHubCollector collector = context.getBean(EventHubCollector.class);
    assertNotNull(collector);
    assertEquals(processorHostName, collector.getProcessorHostName());
}
 
Example 17
Project: JavaStudy   File: Test.java   Source Code and License 5 votes vote down vote up
@org.junit.Test
public void testCustomKeyGenerator(){
    ApplicationContext atc=new AnnotationConfigApplicationContext(RedisStartConfig.class);
    KeyGenerator obj = (KeyGenerator) atc.getBean("customKeyGenerator");
    PrinterUtils.printILog(obj);

}
 
Example 18
Project: azure-spring-boot   File: StorageAutoConfigurationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void createStorageAccountWithValidConnectionStringFormat() {
    System.setProperty(CONNECTION_STRING_PROPERTY, CONNECTION_STRING_WITH_VALID_FORMAT);

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(StorageAutoConfiguration.class);
        context.refresh();

        final CloudStorageAccount cloudStorageAccount = context.getBean(CloudStorageAccount.class);
        assertThat(cloudStorageAccount).isNotNull();
    }

    System.clearProperty(CONNECTION_STRING_PROPERTY);
}
 
Example 19
Project: dubbocloud   File: JavaConfigContainer.java   Source Code and License 5 votes vote down vote up
public void start() {
    String configPath = ConfigUtils.getProperty(SPRING_JAVACONFIG);
    if (configPath == null || configPath.length() == 0) {
        configPath = DEFAULT_SPRING_JAVACONFIG;
    }
    context = new AnnotationConfigApplicationContext(configPath);
    context.start();
}
 
Example 20
Project: tensorflow   File: TwitterSentimentProcessorPropertiesTests.java   Source Code and License 5 votes vote down vote up
@Test
public void vocabularyCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "tensorflow.twitter.vocabulary:/remote");
	context.register(Conf.class);
	context.refresh();
	TwitterSentimentProcessorProperties properties = context.getBean(TwitterSentimentProcessorProperties.class);
	assertThat(properties.getVocabulary(), equalTo(context.getResource("/remote")));
	context.close();
}
 
Example 21
Project: hello-spring   File: Main.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
	                ConditionConfig.class);
	ListService listService = context.getBean(ListService.class);
	System.err.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令为:"
	                + listService.showListCmd());
	context.close();
}
 
Example 22
Project: Mastering-Software-Testing-with-JUnit-5   File: MySpringApplication.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            MySpringApplication.class)) {
        MessageComponent messageComponent = context
                .getBean(MessageComponent.class);
        System.out.println(messageComponent.getMessage());
    }
}
 
Example 23
Project: fo-veilarbjobbsokerkompetanse   File: AbstractIntegrasjonsTest.java   Source Code and License 5 votes vote down vote up
@SneakyThrows
public static void setupContext(Class<?>... classes) {
    DatabaseTestContext.setupContext(System.getProperty("database"));

    setProperty("no.nav.modig.security.sts.url", "111111");
    setProperty("no.nav.modig.security.systemuser.username", "username");
    setProperty("no.nav.modig.security.systemuser.password", "password");

    annotationConfigApplicationContext = new AnnotationConfigApplicationContext(classes);
    annotationConfigApplicationContext.start();
    platformTransactionManager = getBean(PlatformTransactionManager.class);

    MigrationUtils.createTables(getBean(DataSource.class));
}
 
Example 24
Project: sponge   File: SpringAutoStartupTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSpringAutoStartupTrue() throws InterruptedException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(TestConfigAutoStartupTrue.class);
    ctx.start();

    try {
        Engine engine = ctx.getBean(Engine.class);

        assertTrue(engine.isRunning());
        assertFalse(engine.isError());
    } finally {
        ctx.close();
    }
}
 
Example 25
Project: poi-visualizer   File: POIVisualizer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  	final String pckName = POIVisualizer.class.getPackage().getName();
  	try (AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(pckName)) {
  		POIVisualizer visualizer = ctx.getBean(POIVisualizer.class);
  		visualizer.start();
  	}

System.out.println("Exiting");
  }
 
Example 26
Project: azure-spring-boot   File: StoragePropertiesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void canSetProperties() {
    System.setProperty(CONNECTION_STRING_PROPERTY, CONNECTION_STRING);

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);
        context.refresh();

        final StorageProperties properties = context.getBean(StorageProperties.class);
        assertThat(properties.getConnectionString()).isEqualTo(CONNECTION_STRING);
    }

    System.clearProperty(CONNECTION_STRING_PROPERTY);
}
 
Example 27
Project: spring-security-oauth2-boot   File: OAuth2AutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testClientIsNotAuthCode() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(MinimalSecureNonWebApplication.class);
	TestPropertyValues.of("security.oauth2.client.clientId=client").applyTo(context);
	context.refresh();
	assertThat(countBeans(context, ClientCredentialsResourceDetails.class))
			.isEqualTo(1);
	context.close();
}
 
Example 28
Project: Lagerta   File: ReaderConfig.java   Source Code and License 5 votes vote down vote up
public static AnnotationConfigApplicationContext create(ApplicationContext parent) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.setParent(parent);
    context.register(parent.getBean("reader-config", Class.class));
    context.refresh();
    return context;
}
 
Example 29
Project: spring-session-data-mongodb   File: ReactiveMongoWebSessionConfigurationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void overridingMongoSessionConverterWithBeanShouldWork() throws IllegalAccessException {

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(OverrideSessionConverterConfig.class);
	this.context.refresh();

	ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class);

	AbstractMongoSessionConverter converter = findMongoSessionConverter(repository);

	assertThat(converter)
		.extracting(AbstractMongoSessionConverter::getClass)
		.contains(JacksonMongoSessionConverter.class);
}
 
Example 30
Project: mastering-junit5   File: MySpringApplication.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            MySpringApplication.class)) {
        MessageComponent messageComponent = context
                .getBean(MessageComponent.class);
        System.out.println(messageComponent.getMessage());
    }
}
 
Example 31
Project: quickfixj-spring-boot-starter   File: AbstractEndpointTests.java   Source Code and License 5 votes vote down vote up
@Test
public void isEnabledFallbackToEnvironment() throws Exception {
    this.context = new AnnotationConfigApplicationContext();
    PropertySource<?> propertySource = new MapPropertySource("test", Collections
            .<String, Object>singletonMap(this.property + ".enabled", false));
    this.context.getEnvironment().getPropertySources().addFirst(propertySource);
    this.context.register(this.configClass);
    this.context.refresh();
    assertThat(getEndpointBean().isEnabled()).isFalse();
}
 
Example 32
Project: reactive.loanbroker.system   File: LoanBrokerTests.java   Source Code and License 5 votes vote down vote up
@Before
public void startServer(){
    if(!isServerStarted) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
        ac.register(TestingConfiguration.class);
        ac.refresh();

        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(WebHttpHandlerBuilder.webHandler(new DispatcherHandler(ac)).build());
        HttpServer httpServer = HttpServer.create(PORT);
        httpServer.newHandler(adapter).block();
        isServerStarted = true;
    }
}
 
Example 33
Project: SpringTutorial   File: JavaConfigTestClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {

	 AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(CoreJavaConfig.class);

		Payment pmt=(Payment) ctx.getBean("dummypayment");
      pmt.pay();
      ctx.registerShutdownHook();
	}
 
Example 34
Project: hekate   File: SpringInjectionService.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ConfigurationContext ctx) {
    // Application context for autowiring.
    AnnotationConfigApplicationContext autowireCtx = new AnnotationConfigApplicationContext() {
        @Override
        public String toString() {
            return SpringInjectionService.class.getSimpleName() + "Context";
        }
    };

    // Expose services for autowiring.
    ConfigurableListableBeanFactory factory = autowireCtx.getBeanFactory();

    uniqueServices(ctx).forEach(service -> {
        factory.registerResolvableDependency(service.getClass(), service);

        for (Class<?> type : service.getClass().getInterfaces()) {
            factory.registerResolvableDependency(type, service);
        }
    });

    autowireCtx.refresh();

    autowireCtx.setParent(parentCtx);

    autowire = autowireCtx.getAutowireCapableBeanFactory();
}
 
Example 35
Project: hello-spring   File: Main.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
	DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
	DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
	DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
	DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

	System.out.println("s1与s2是否相等:" + s1.equals(s2));
	System.out.println("p1与p2是否相等:" + p1.equals(p2));

	context.close();
}
 
Example 36
Project: spring-reactive-sample   File: Application.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    PostRepository posts = new PostRepository();
    PostHandler postHandler = new PostHandler(posts);
    Routes routesBean = new Routes(postHandler);

    context.registerBean(PostRepository.class, () -> posts);
    context.registerBean(PostHandler.class, () -> postHandler);
    context.registerBean(Routes.class, () -> routesBean);
    context.registerBean(WebHandler.class, () -> RouterFunctions.toWebHandler(routesBean.routes(), HandlerStrategies.builder().build()));
    context.refresh();

    nettyContext(context).onClose().block();
}
 
Example 37
Project: nixmash-blog   File: BatchLauncher.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        PropertySource commandLineProperties = new
                SimpleCommandLinePropertySource(args);

        AnnotationConfigApplicationContext context= new
                AnnotationConfigApplicationContext();

        context.getEnvironment().getPropertySources().addFirst(commandLineProperties);
        context.register(ApplicationConfiguration.class);
        context.refresh();
    }
 
Example 38
Project: spring-reactive-sample   File: AppIntializer.java   Source Code and License 5 votes vote down vote up
@Override
protected ApplicationContext createApplicationContext() {
    Class<?>[] configClasses = getConfigClasses();
    Assert.notEmpty(configClasses, "No Spring configuration provided.");
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClasses);
    return context;
}
 
Example 39
Project: azure-spring-boot   File: ServiceBusPropertiesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void canSetQueueProperties() {
    System.setProperty(Constants.CONNECTION_STRING_PROPERTY, Constants.INVALID_CONNECTION_STRING);
    System.setProperty(Constants.QUEUE_NAME_PROPERTY, Constants.QUEUE_NAME);
    System.setProperty(Constants.QUEUE_RECEIVE_MODE_PROPERTY, Constants.QUEUE_RECEIVE_MODE.name());
    System.setProperty(Constants.TOPIC_NAME_PROPERTY, Constants.TOPIC_NAME);
    System.setProperty(Constants.SUBSCRIPTION_NAME_PROPERTY, Constants.SUBSCRIPTION_NAME);
    System.setProperty(Constants.SUBSCRIPTION_RECEIVE_MODE_PROPERTY, Constants.SUBSCRIPTION_RECEIVE_MODE.name());

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);
        context.refresh();
        final ServiceBusProperties properties = context.getBean(ServiceBusProperties.class);

        assertThat(properties.getConnectionString()).isEqualTo(Constants.INVALID_CONNECTION_STRING);
        assertThat(properties.getQueueName()).isEqualTo(Constants.QUEUE_NAME);
        assertThat(properties.getQueueReceiveMode()).isEqualTo(Constants.QUEUE_RECEIVE_MODE);
        assertThat(properties.getTopicName()).isEqualTo(Constants.TOPIC_NAME);
        assertThat(properties.getSubscriptionName()).isEqualTo(Constants.SUBSCRIPTION_NAME);
        assertThat(properties.getSubscriptionReceiveMode()).isEqualTo(Constants.SUBSCRIPTION_RECEIVE_MODE);
    }

    System.clearProperty(Constants.CONNECTION_STRING_PROPERTY);
    System.clearProperty(Constants.QUEUE_NAME_PROPERTY);
    System.clearProperty(Constants.QUEUE_RECEIVE_MODE_PROPERTY);
    System.clearProperty(Constants.TOPIC_NAME_PROPERTY);
    System.clearProperty(Constants.SUBSCRIPTION_NAME_PROPERTY);
    System.clearProperty(Constants.SUBSCRIPTION_RECEIVE_MODE_PROPERTY);
}
 
Example 40
Project: spring-cloud-dashboard   File: OnSecurityEnabledAndOAuth2EnabledTests.java   Source Code and License 5 votes vote down vote up
@Test
public void both() throws Exception {
	AnnotationConfigApplicationContext context = load(Config.class,
		"security.basic.enabled:true", "security.oauth2");
	assertThat(context.containsBean("myBean"), equalTo(false));
	context.close();
}
 
Example 41
Project: azure-spring-boot   File: AADAuthenticationFilterPropertiesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void emptySettingsNotAllowed() {
    System.setProperty(Constants.CLIENT_ID_PROPERTY, "");
    System.setProperty(Constants.CLIENT_SECRET_PROPERTY, "");

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(Config.class);

        Exception exception = null;
        try {
            context.refresh();
        } catch (Exception e) {
            exception = e;
        }

        assertThat(exception).isNotNull();
        assertThat(exception).isExactlyInstanceOf(BeanCreationException.class);
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientId': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'clientSecret': rejected value []");
        assertThat(exception.getCause().getMessage()).contains(
                "Field error in object " +
                        "'azure.activedirectory' on field 'activeDirectoryGroups': rejected value [null]");
    }

    System.clearProperty(Constants.CLIENT_ID_PROPERTY);
    System.clearProperty(Constants.CLIENT_SECRET_PROPERTY);
}
 
Example 42
Project: spring4.x-project   File: Main.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			PrePostConfig.class);

	BeanWayService beanWayService = context.getBean(BeanWayService.class);
	JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);

	context.close();
}
 
Example 43
Project: spring-reactive-sample   File: Application.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);  // (1)

    Tomcat tomcatServer = context.getBean(Tomcat.class);
    tomcatServer.start();

    System.out.println("Press ENTER to exit.");
    System.in.read();
}
 
Example 44
Project: spring4.x-project   File: Main.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
	 
	 AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
	 
	 for(int i =0 ;i<10;i++){
		 asyncTaskService.executeAsyncTask(i);
		 asyncTaskService.executeAsyncTaskPlus(i);
        }
        context.close();
}
 
Example 45
Project: factcast   File: EventsDocumentation0Test.java   Source Code and License 5 votes vote down vote up
@Override
public ResourceConfig configure() {
    ResourceConfig rc = new FactCastRestApplication();
    ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    rc.property("contextConfig", ctx);

    rc.register(SpringLifecycleListener.class);
    rc.register(RequestContextFilter.class);

    return rc;
}
 
Example 46
Project: spring-boot-rocketmq-starter   File: RocketMqAutoConfigurationTest.java   Source Code and License 5 votes vote down vote up
private void load(boolean refresh, String... environment) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(RocketMqAutoConfiguration.class);
    EnvironmentTestUtils.addEnvironment(ctx, environment);
    if (refresh) {
        ctx.refresh();
    }
    this.context = ctx;
}
 
Example 47
Project: spring-cloud-dashboard   File: OnSecurityEnabledAndOAuth2EnabledTests.java   Source Code and License 5 votes vote down vote up
@Test
public void both2() throws Exception {
	AnnotationConfigApplicationContext context = load(Config.class,
		"security.basic.enabled:true", "security.oauth2.client.client-id:12345");
	assertThat(context.containsBean("myBean"), equalTo(true));
	context.close();
}
 
Example 48
Project: spring-reactive-sample   File: Application.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);  // (1)
    Server server = context.getBean(Server.class);
    server.start();
    server.join();

    System.out.println("Press ENTER to exit.");
    System.in.read();
}
 
Example 49
Project: quickfixj-spring-boot-starter   File: AbstractEndpointTests.java   Source Code and License 5 votes vote down vote up
@Test
public void isSensitiveOverrideWithGlobal() throws Exception {
    this.context = new AnnotationConfigApplicationContext();
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("endpoint.sensitive", this.sensitive);
    properties.put(this.property + ".sensitive", String.valueOf(!this.sensitive));
    PropertySource<?> propertySource = new MapPropertySource("test", properties);
    this.context.getEnvironment().getPropertySources().addFirst(propertySource);
    this.context.register(this.configClass);
    this.context.refresh();
    assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive);
}
 
Example 50
Project: nixmash-blog   File: JpaLauncher.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(ApplicationConfig.class);
		ctx.refresh();
		System.out.println("Spring Framework Version: " + SpringVersion.getVersion());
		System.out.println("Spring Boot Version: " + SpringBootVersion.getVersion());
		JpaUI ui = ctx.getBean(JpaUI.class);
		ui.init();
		ctx.close();
	}
 
Example 51
Project: morphia-spring-boot-starter   File: MorphiaUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCallGetPackageName_ShouldReturnAPackageName() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationTest.class);
    List<String> applicationPackageName = MorphiaUtils.getApplicationPackageName(context);
    assertThat(applicationPackageName.size(), is(1));
    assertThat(applicationPackageName.get(0), is("io.github.ganchix.morphia.utils.context.normal"));
}
 
Example 52
Project: tensorflow-spring-cloud-stream-app-starters   File: TwitterSentimentProcessorPropertiesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void vocabularyLocationCanBeCustomized() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	EnvironmentTestUtils.addEnvironment(context, "inception.vocabularyLocation:/remote");
	context.register(Conf.class);
	context.refresh();
	TwitterSentimentProcessorProperties properties = context.getBean(TwitterSentimentProcessorProperties.class);
	assertThat(properties.getVocabularyLocation(), equalTo(context.getResource("/remote")));
}
 
Example 53
Project: spring-cloud-vault-connector   File: StubCloudConnectorTest.java   Source Code and License 5 votes vote down vote up
protected ApplicationContext getTestApplicationContext(Class<?> configClass,
		ServiceInfo... serviceInfos) {
	final CloudConnector stubCloudConnector = CloudTestUtil
			.getTestCloudConnector(serviceInfos);

	return new AnnotationConfigApplicationContext(configClass) {
		@Override
		protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
			CloudFactory cloudFactory = new CloudFactory();
			cloudFactory.registerCloudConnector(stubCloudConnector);
			getBeanFactory().registerSingleton(MOCK_CLOUD_BEAN_NAME, cloudFactory);
			super.prepareBeanFactory(beanFactory);
		}
	};
}
 
Example 54
Project: azure-spring-boot   File: MediaServicesAutoConfigurationTest.java   Source Code and License 5 votes vote down vote up
private void createAndVerifyMediaContract() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
        context.register(MediaServicesAutoConfiguration.class);
        context.refresh();

        final MediaContract mediaContract = context.getBean(MediaContract.class);
        assertThat(mediaContract).isNotNull();
        assertThat(mediaContract).isExactlyInstanceOf(MediaExceptionProcessor.class);
    }
}
 
Example 55
Project: JRediClients   File: RedissonSpringCacheShortTTLTest.java   Source Code and License 5 votes vote down vote up
@Parameterized.Parameters(name = "{index} - {0}")
public static Iterable<Object[]> data() throws IOException, InterruptedException {
    if (p == null) {
        p = RedisRunner.startDefaultRedisServerInstance();
    }
    return Arrays.asList(new Object[][]{
        {new AnnotationConfigApplicationContext(Application.class)},
        {new AnnotationConfigApplicationContext(JsonConfigApplication.class)},
    });
}
 
Example 56
Project: rocketmq-spring-boot-starter   File: MQConsumerAutoConfigurationTest.java   Source Code and License 5 votes vote down vote up
private void prepareApplicationContextCMOrderly() {
    this.context = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(this.context, "rocketmq.name-server-address:127.0.0.1:9876");
    this.context.register(TestConsumerOrderly.class);
    this.context.register(MQConsumerAutoConfiguration.class);
    this.context.refresh();
}
 
Example 57
Project: spring-cloud-dashboard   File: OnSecurityEnabledAndOAuth2EnabledTests.java   Source Code and License 5 votes vote down vote up
@Test
public void oneTrueOneFalse() throws Exception {
	AnnotationConfigApplicationContext context = load(Config.class,
		"security.basic.enabled:false", "security.oauth2");
	assertThat(context.containsBean("myBean"), equalTo(false));
	context.close();
}
 
Example 58
Project: spring-session-data-mongodb   File: ReactiveMongoWebSessionConfigurationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void reactiveAndBlockingMongoOperationsShouldEnsureIndexing() {

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(ConfigWithReactiveAndImperativeMongoOperations.class);
	this.context.refresh();

	MongoOperations operations = this.context.getBean(MongoOperations.class);
	IndexOperations indexOperations = this.context.getBean(IndexOperations.class);

	verify(operations, times(1)).indexOps((String) any());
	verify(indexOperations, times(1)).getIndexInfo();
	verify(indexOperations, times(1)).ensureIndex(any());
}
 
Example 59
Project: gauravbytes   File: App.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	// using try with resources so that this context closes automatically
	try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
	    WelcomeGbConfig.class);) {
		GreetingService greetingService = context.getBean(GreetingService.class);
		greetingService.greet();
	}
}
 
Example 60
Project: training-sample   File: BeanTest.java   Source Code and License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
	context = new AnnotationConfigApplicationContext(AppConfig.class);
}