org.springframework.context.support.ClassPathXmlApplicationContext Java Examples

The following examples show how to use org.springframework.context.support.ClassPathXmlApplicationContext. 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: TestBase.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  // 获取spring配置文件,生成上下文
  context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
  //   ((ClassPathXmlApplicationContext) context).start();

  Service service = context.getBean(Service.class);
  service.run();

  System.out.println("start...");
  System.out.println("===================================================================");

  ChannelEthereumService channelEthereumService = new ChannelEthereumService();
  channelEthereumService.setChannelService(service);
  channelEthereumService.setTimeout(10000);
  web3j = Web3j.build(channelEthereumService, service.getGroupId());
  // EthBlockNumber ethBlockNumber = web3.ethBlockNumber().send();

}
 
Example #2
Source File: ConfigTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemPropertyOverrideMultiProtocol() throws Exception {
    System.setProperty("dubbo.protocol.dubbo.port", "20814");
    System.setProperty("dubbo.protocol.rmi.port", "10914");
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/override-multi-protocol.xml");
    providerContext.start();
    try {
        ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
        assertEquals(20814, dubbo.getPort().intValue());
        ProtocolConfig rmi = (ProtocolConfig) providerContext.getBean("rmi");
        assertEquals(10914, rmi.getPort().intValue());
    } finally {
        System.setProperty("dubbo.protocol.dubbo.port", "");
        System.setProperty("dubbo.protocol.rmi.port", "");
        providerContext.stop();
        providerContext.close();
    }
}
 
Example #3
Source File: ConfigTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_returnSerializationFail() throws Exception {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/demo-provider-UnserializableBox.xml");
    providerContext.start();
    try {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/init-reference.xml");
        ctx.start();
        try {
            DemoService demoService = (DemoService)ctx.getBean("demoService");
            try {
                demoService.getBox();
                fail();
            } catch (RpcException expected) {
                assertThat(expected.getMessage(), containsString("must implement java.io.Serializable"));
            }
        } finally {
            ctx.stop();
            ctx.close();
        }
    } finally {
        providerContext.stop();
        providerContext.close();
    }
}
 
Example #4
Source File: AtAspectJAfterThrowingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAccessThrowable() throws Exception {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	ITestBean bean = (ITestBean) ctx.getBean("testBean");
	ExceptionHandlingAspect aspect = (ExceptionHandlingAspect) ctx.getBean("aspect");

	assertTrue(AopUtils.isAopProxy(bean));
	try {
		bean.unreliableFileOperation();
	}
	catch (IOException e) {
		//
	}

	assertEquals(1, aspect.handled);
	assertNotNull(aspect.lastException);
}
 
Example #5
Source File: SimpleConfigTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testFooService() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getConfigLocations(), getClass());

	FooService fooService = ctx.getBean("fooServiceImpl", FooService.class);
	ServiceInvocationCounter serviceInvocationCounter = ctx.getBean("serviceInvocationCounter", ServiceInvocationCounter.class);

	String value = fooService.foo(1);
	assertEquals("bar", value);

	Future<?> future = fooService.asyncFoo(1);
	assertTrue(future instanceof FutureTask);
	assertEquals("bar", future.get());

	assertEquals(2, serviceInvocationCounter.getCount());

	fooService.foo(1);
	assertEquals(3, serviceInvocationCounter.getCount());
}
 
Example #6
Source File: QuartzSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void schedulerAccessorBean() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);
	ClassPathXmlApplicationContext ctx = context("schedulerAccessorBean.xml");
	Thread.sleep(3000);
	try {
		QuartzTestBean exportService = (QuartzTestBean) ctx.getBean("exportService");
		QuartzTestBean importService = (QuartzTestBean) ctx.getBean("importService");

		assertEquals("doImport called exportService", 0, exportService.getImportCount());
		assertEquals("doExport not called on exportService", 2, exportService.getExportCount());
		assertEquals("doImport not called on importService", 2, importService.getImportCount());
		assertEquals("doExport called on importService", 0, importService.getExportCount());
	}
	finally {
		ctx.close();
	}
}
 
Example #7
Source File: TestContextSourceFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-testContextSource.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example #8
Source File: BshScriptFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nonStaticPrototypeScript() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass());
	ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
	ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype");

	assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger));
	assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable);

	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Hello World!", messenger2.getMessage());
	messenger.setMessage("Bye World!");
	messenger2.setMessage("Byebye World!");
	assertEquals("Bye World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());

	Refreshable refreshable = (Refreshable) messenger;
	refreshable.refresh();

	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());
	assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount());
}
 
Example #9
Source File: SessionFactoryTest.java    From scada with MIT License 6 votes vote down vote up
@Test
public void testUser(){
	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	UserService userService = (UserService) context.getBean("userService");
	User user = new User();
	user.setUsername("menghan");
	user.setLoginName("meng");
	user.setLoginPwd("han");
	user.setAddress("ƽ��");
	user.setBirthday("");
	user.setContactTel("15001185667");
	user.setSex("��");
	user.setIsDuty("��");
	user.setEmail("[email protected]");
	user.setRemark("��");
	user.setRightsId(5);
	user.setOnDutyDate(new Date());
	userService.save(user);
}
 
Example #10
Source File: AsyncConsumer.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
    context.start();
    
    final AsyncService asyncService = (AsyncService)context.getBean("asyncService");
    
    Future<String> f = RpcContext.getContext().asyncCall(new Callable<String>() {
        public String call() throws Exception {
            return asyncService.sayHello("async call request");
        }
    });
    
    System.out.println("async call ret :" + f.get());
    
    RpcContext.getContext().asyncCall(new Runnable() {
        public void run() {
            asyncService.sayHello("oneway call request1");
            asyncService.sayHello("oneway call request2");
        }
    });
    
    System.in.read();
}
 
Example #11
Source File: MybatisDALTest.java    From uncode-dal-all with GNU General Public License v2.0 5 votes vote down vote up
public static void startService(){
	try {
		context = new ClassPathXmlApplicationContext(new String[] { "application.xml"});
		context.start();
		baseDAL = (BaseDAL) context.getBean("baseDAL");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #12
Source File: TestAdminDao.java    From EasyHousing with MIT License 5 votes vote down vote up
@Test
public void Test3(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//��ʼ������
	AdministratorDao administratorDao = (AdministratorDao) ac.getBean("administratorDao");
	Administrator u = new Administrator();
	u.setAdministratorDepartment("��̨");
	u.setAdministratorName("fly");
	u.setAdministratorPassword("1996511");
	u.setAdministratorSex("��");
	u.setAdministratorId(0);
	administratorDao.updateAdministrator(u);
	System.out.println("-------");
}
 
Example #13
Source File: GroovyScriptFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testWithTwoClassesDefinedInTheOneGroovyFile_WrongClassFirst() throws Exception {
	try {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass());
		ctx.getBean("messenger", Messenger.class);
		fail("Must have failed: two classes defined in GroovyScriptFactory source, non-Messenger class defined first.");
	}
	// just testing for failure here, hence catching Exception...
	catch (Exception expected) {
	}
}
 
Example #14
Source File: PropertyDependentAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void checkAtAspectJAspect(String appContextFile) {
	ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile, getClass());
	ICounter counter = (ICounter) context.getBean("counter");
	assertTrue("Proxy didn't get created", counter instanceof Advised);

	counter.increment();
	JoinPointMonitorAtAspectJAspect callCountingAspect = (JoinPointMonitorAtAspectJAspect)context.getBean("monitoringAspect");
	assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions);
	assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions);
}
 
Example #15
Source File: ContextNamespaceHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void propertyPlaceholderSystemProperties() {
	String value = System.setProperty("foo", "spam");
	try {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"contextNamespaceHandlerTests-system.xml", getClass());
		assertEquals("spam", applicationContext.getBean("string"));
		assertEquals("none", applicationContext.getBean("fallback"));
	}
	finally {
		if (value != null) {
			System.setProperty("foo", value);
		}
	}
}
 
Example #16
Source File: Application.java    From Spring with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	final ClassPathXmlApplicationContext context =
			new ClassPathXmlApplicationContext("spring/application-context.xml");
	bookRepository = context.getBean(BookRepository.class);

	/*CRUD*/
	create();
	read();
	update();
	delete();
}
 
Example #17
Source File: SpringTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * assert method that is used by all the test method to send and receive messages
 * based on each spring configuration.
 *
 * @param config
 * @throws Exception
 */
protected void assertSenderConfig(String config) throws Exception {
   Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader());
   context = new ClassPathXmlApplicationContext(config);

   consumer = (SpringConsumer) context.getBean("consumer");
   assertTrue("Found a valid consumer", consumer != null);

   consumer.start();

   // Wait a little to drain any left over messages.
   Thread.sleep(1000);
   consumer.flushMessages();

   producer = (SpringProducer) context.getBean("producer");
   assertTrue("Found a valid producer", producer != null);

   producer.start();

   // lets sleep a little to give the JMS time to dispatch stuff
   consumer.waitForMessagesToArrive(producer.getMessageCount());

   // now lets check that the consumer has received some messages
   List<Message> messages = consumer.flushMessages();
   LOG.info("Consumer has received messages....");
   for (Iterator<Message> iter = messages.iterator(); iter.hasNext(); ) {
      Object message = iter.next();
      LOG.info("Received: " + message);
   }

   assertEquals("Message count", producer.getMessageCount(), messages.size());
}
 
Example #18
Source File: MapReduceBeanTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    System.setProperty(NpeUtils.NPE_OU_PROPERTY, "iamnotaperson");
    System.setProperty("dw.metadatahelper.all.auths", "A,B,C,D");
    DatawaveUser user = new DatawaveUser(SubjectIssuerDNPair.of(userDN, "CN=ca, OU=acme"), UserType.USER, Arrays.asList(auths),
                    Collections.singleton("AuthorizedUser"), null, 0L);
    principal = new DatawavePrincipal(Collections.singletonList(user));
    
    applicationContext = new ClassPathXmlApplicationContext("classpath:*datawave/mapreduce/MapReduceJobs.xml");
    Whitebox.setInternalState(bean, MapReduceConfiguration.class, applicationContext.getBean(MapReduceConfiguration.class));
}
 
Example #19
Source File: FormBasedDetailsServiceTest.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public void init(){
	_logger.info("init ...");
	
	_logger.info("Application dir "+System.getProperty("user.dir"));
	context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"});
	WebContext.applicationContext=context;
	getservice();
	System.out.println("init ...");
	
}
 
Example #20
Source File: MongoTest.java    From uncode-dal-all with GNU General Public License v2.0 5 votes vote down vote up
@Test
  public void testDeleteByCriteria(){
  	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "application.xml" });
context.start();
MongoDAL mongoDAL = (MongoDAL) context.getBean("mongoDAL");
      QueryCriteria queryCriteria = new QueryCriteria();
      queryCriteria.setTable("news");
      Criteria critera = queryCriteria.createCriteria();
      critera.andColumnEqualTo("status", 1);
      int result = mongoDAL.deleteByCriteria(queryCriteria);
      System.out.println(result);
  }
 
Example #21
Source File: CustomConsumerFactoryPostProcessor.java    From fountain with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    PluggableConsumeActorEnabled meta =
            AnnotationUtils.findAnnotation(bean.getClass(), PluggableConsumeActorEnabled.class);

    if (meta != null) {
        if (!(bean instanceof ConsumeActorAware)) {
            LOGGER.error(
                    "PluggableConsumeActorEnabled annotaion can only be used on ConsumeActorAware "
                            + "implementation");
        }

        LOGGER.info("Start to init IoC container by loading XML bean definitions from {}",
                CLASSPATH_PREFIX + resourceXmlPath);
        iocContainer = new ClassPathXmlApplicationContext(CLASSPATH_PREFIX + resourceXmlPath);
        iocContainer.setParent(applicationContext);
        Map<String, ConsumeActor> consumeActorBeanMap = iocContainer.getBeansOfType(ConsumeActor.class);

        if (CollectionUtils.isEmpty(consumeActorBeanMap)) {
            throw new BeanInitializationException(
                    "No ConsumeActor bean found in " + CLASSPATH_PREFIX + resourceXmlPath);
        }

        if (consumeActorBeanMap.size() > 1) {
            LOGGER.warn("Multiple ConsumeActor beans found in {}{}, and the first one found will be used"
                    + " only", CLASSPATH_PREFIX, resourceXmlPath);
        } else {
            LOGGER.info("Find one ConsumeActor which will be plugged into Consumer as an actor");
        }

        ConsumeActor consumeActor = consumeActorBeanMap.values().toArray(new ConsumeActor[] {})[0];
        ((ConsumeActorAware) bean).setConsumeActor(consumeActor);
    }
    return bean;
}
 
Example #22
Source File: DoradoDemo.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException, InterruptedException, IOException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
    final Echo.Iface client = context.getBean("clientProxy", Echo.Iface.class);

    Thread[] threads = new Thread[num];

    for (int i = 0; i < num; i++) {
        final int finalI = i;
        threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                String result = null;
                Random random = new Random();
                for (int j = 0; j < num; j++) {
                    try {
                        result = client.echo("hello" + finalI + "," + j);
                        Thread.sleep(random.nextInt(100));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    assert ("echo: hello" + finalI + "," + j).equals(result);
                }
            }
        });
        threads[i].start();
    }

    for (Thread t : threads) {
        t.join();
    }

    context.destroy();
    System.exit(0);
}
 
Example #23
Source File: ConfigTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemPropertyOverrideProtocol() throws Exception {
    System.setProperty("dubbo.protocol.port", "20812");
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/override-protocol.xml");
    providerContext.start();
    try {
        ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
        assertEquals(20812, dubbo.getPort().intValue());
    } finally {
        System.setProperty("dubbo.protocol.port", "");
        providerContext.stop();
        providerContext.close();
    }
}
 
Example #24
Source File: IgniteSpringBeanSpringResourceInjectionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void run() {
    appCtx = new ClassPathXmlApplicationContext(springCfgLocation);

    Integer beanToInject = (Integer)appCtx.getBean(beanToInjectName);

    assertEquals(beanToInject, getInjectedBean());
}
 
Example #25
Source File: Application.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
    context.start();

    UserService userService = context.getBean("userService", UserService.class);
    User user = userService.getUser(1L);
    System.out.println("result: " + user);

    DemoService demoService = context.getBean("demoService", DemoService.class);
    String hello = demoService.sayHello("world");
    System.out.println("result: " + hello);
}
 
Example #26
Source File: ComponentScanParserWithUserDefinedStrategiesTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidClassNameScopeMetadataResolver() {
	try {
		new ClassPathXmlApplicationContext(
				"org/springframework/context/annotation/invalidClassNameScopeResolverTests.xml");
		fail("should have failed: no such class");
	}
	catch (BeansException e) {
		// expected
	}
}
 
Example #27
Source File: AsyncProvider.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    new EmbeddedZooKeeper(2181, false).start();

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/async-provider.xml");
    context.start();

    System.out.println("dubbo service started");
    new CountDownLatch(1).await();
}
 
Example #28
Source File: SubtypeSensitiveMatchingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
	nonSerializableBean = (NonSerializableFoo) ctx.getBean("testClassA");
	serializableBean = (SerializableFoo) ctx.getBean("testClassB");
	bar = (Bar) ctx.getBean("testClassC");
}
 
Example #29
Source File: AdvisorAdapterRegistrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvisorAdapterRegistrationManagerNotPresentInContext() {
	ClassPathXmlApplicationContext ctx =
		new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-without-bpp.xml", getClass());
	ITestBean tb = (ITestBean) ctx.getBean("testBean");
	// just invoke any method to see if advice fired
	try {
		tb.getName();
		fail("Should throw UnknownAdviceTypeException");
	}
	catch (UnknownAdviceTypeException ex) {
		// expected
		assertEquals(0, getAdviceImpl(tb).getInvocationCounter());
	}
}
 
Example #30
Source File: GroovyScriptFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testStaticScriptWithInstance() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance"));
	Messenger messenger = (Messenger) ctx.getBean("messengerInstance");

	assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger));
	assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable);

	String desiredMessage = "Hello World!";
	assertEquals("Message is incorrect", desiredMessage, messenger.getMessage());
	assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger));
}