Java Code Examples for org.springframework.context.support.ClassPathXmlApplicationContext

The following examples show how to use org.springframework.context.support.ClassPathXmlApplicationContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: WeBASE-Front   Source File: TestBase.java    License: 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 Project: scada   Source File: SessionFactoryTest.java    License: 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 3
Source Project: dubbox   Source File: ConfigTest.java    License: 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 4
Source Project: dubbox   Source File: ConfigTest.java    License: 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 5
@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 6
Source Project: java-technology-stack   Source File: BshScriptFactoryTests.java    License: 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 7
Source Project: spring4-understanding   Source File: SimpleConfigTests.java    License: 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 8
Source Project: spring-analysis-note   Source File: QuartzSupportTests.java    License: 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 9
@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 10
Source Project: dubbox   Source File: AsyncConsumer.java    License: 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 Project: dubbo-samples   Source File: Application.java    License: 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 12
@Test
public void givenXMLConfigFile_whenUsingSetterBasedBeanInjection_thenCorrectHelmName() {
    final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInjection-setter.xml");

    final Ship shipSetterBean = (Ship) applicationContext.getBean("ship");
    Assert.assertEquals(HELM_NAME, shipSetterBean.getHelm().getBrandOfHelm());
}
 
Example 13
@Test
public void testCustomScopeMetadataResolver() {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
			"org/springframework/context/annotation/customScopeResolverTests.xml");
	BeanDefinition bd = context.getBeanFactory().getBeanDefinition("fooServiceImpl");
	assertEquals("myCustomScope", bd.getScope());
	assertFalse(bd.isSingleton());
}
 
Example 14
@Override
@Test
public void sampleConfiguration() {
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"annotation-driven-sample-config.xml", getClass());
	testSampleConfiguration(context);
}
 
Example 15
Source Project: dubbo-samples   Source File: AttachmentConsumer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/attachment-consumer.xml");
    context.start();

    AttachmentService attachmentService = context.getBean("demoService", AttachmentService.class);
    RpcContext.getContext().setAttachment("index", "1");

    String hello = attachmentService.sayHello("world");
    System.out.println(hello);

    // attachment only affective once
    hello = attachmentService.sayHello("world");
    System.out.println(hello);
}
 
Example 16
@Test
public void testPostProcessBeforeInitialization() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
               "/conf/baseLdapPathPostProcessorTestContext.xml");
	DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class);

	DistinguishedName base = tested.getBase();
	assertThat(base).isNotNull();
	assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com"));

       DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class);
       assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=261consulting,dc=com"));
   }
 
Example 17
Source Project: geekbang-lessons   Source File: BeanAliasDemo.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 配置 XML 配置文件
    // 启动 Spring 应用上下文
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean-definitions-context.xml");
    // 通过别名 xiaomage-user 获取曾用名 user 的 bean
    User user = beanFactory.getBean("user", User.class);
    User xiaomageUser = beanFactory.getBean("xiaomage-user", User.class);
    System.out.println("xiaomage-user 是否与 user Bean 相同:" + (user == xiaomageUser));
}
 
Example 18
@Override
@Test
public void defaultContainerFactory() {
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"annotation-driven-default-container-factory.xml", getClass());
	testDefaultContainerFactoryConfiguration(context);
}
 
Example 19
Source Project: eagle   Source File: SpringContainer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    String configPath = System.getProperty(SPRING_CONFIG);
    if (Strings.isNullOrEmpty(configPath)) {
        configPath = DEFAULT_SPRING_CONFIG;
    }
    context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+"));
    context.start();
}
 
Example 20
Source Project: dubbox   Source File: ConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSystemPropertyOverrideXmlDefault() throws Exception {
    System.setProperty("dubbo.application.name", "sysover");
    System.setProperty("dubbo.application.owner", "sysowner");
    System.setProperty("dubbo.registry.address", "N/A");
    System.setProperty("dubbo.protocol.name", "dubbo");
    System.setProperty("dubbo.protocol.port", "20819");
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/system-properties-override-default.xml");
    providerContext.start();
    try {
        ServiceConfig<DemoService> service = (ServiceConfig<DemoService>) providerContext.getBean("demoServiceConfig");
        assertEquals("sysover", service.getApplication().getName());
        assertEquals("sysowner", service.getApplication().getOwner());
        assertEquals("N/A", service.getRegistry().getAddress());
        assertEquals("dubbo", service.getProtocol().getName());
        assertEquals(20819, service.getProtocol().getPort().intValue());
    } finally {
        System.setProperty("dubbo.application.name", "");
        System.setProperty("dubbo.application.owner", "");
        System.setProperty("dubbo.registry.address", "");
        System.setProperty("dubbo.protocol.name", "");
        System.setProperty("dubbo.protocol.port", "");
        providerContext.stop();
        providerContext.close();
    }
}
 
Example 21
Source Project: dubbox   Source File: ConfigTest.java    License: 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 22
Source Project: cxf   Source File: JavaFirstPolicyServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBindingClientCertAlternativePolicy() {
    System.setProperty("testutil.ports.JavaFirstPolicyServer.3", PORT3);

    ClassPathXmlApplicationContext clientContext = new ClassPathXmlApplicationContext(new String[] {
        "org/apache/cxf/systest/ws/policy/sslcertclient.xml"
    });

    BindingSimpleService simpleService = clientContext.getBean("BindingSimpleServiceClient",
                                                                     BindingSimpleService.class);

    try {
        simpleService.doStuff();
        fail("Expected exception as no credentials");
    } catch (SOAPFaultException e) {
        // expected
    }

    WSS4JOutInterceptor wssOut = addToClient(simpleService);

    wssOut.setProperties(getNoPasswordProperties("alice"));
    simpleService.doStuff();

    wssOut.setProperties(getPasswordProperties("alice", "password"));

    // this is successful because the alternative policy allows a password to be specified.
    simpleService.doStuff();

    clientContext.close();
}
 
Example 23
Source Project: java-technology-stack   Source File: BenchmarkTests.java    License: MIT License 5 votes vote down vote up
private long testMix(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated mixed invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);

	for (int i = 0; i < howmany; i++) {
		// Hit all 3 joinpoints
		adrian.getAge();
		adrian.getName();
		adrian.setAge(i);

		// Invoke three non-advised methods
		adrian.getDoctor();
		adrian.getLawyer();
		adrian.getSpouse();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
Example 24
Source Project: java-technology-stack   Source File: GroovyScriptFactoryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testResourceScriptFromTag() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass());
	Messenger messenger = (Messenger) ctx.getBean("messenger");
	CallCounter countingAspect = (CallCounter) ctx.getBean("getMessageAspect");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertFalse(messenger instanceof Refreshable);
	assertEquals(0, countingAspect.getCalls());
	assertEquals("Hello World!", messenger.getMessage());
	assertEquals(1, countingAspect.getCalls());

	ctx.close();
	assertEquals(-200, countingAspect.getCalls());
}
 
Example 25
@Test
public void componentScanWithAutowiredQualifier() {
	ClassPathXmlApplicationContext context = loadContext("componentScanWithAutowiredQualifierTests.xml");
	AutowiredQualifierFooService fooService = (AutowiredQualifierFooService) context.getBean("fooService");
	assertTrue(fooService.isInitCalled());
	assertEquals("bar", fooService.foo(123));
	context.close();
}
 
Example 26
Source Project: dubbox   Source File: ConfigTest.java    License: 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 27
@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 28
@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
@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));
}
 
Example 30
Source Project: EasyHousing   Source File: TestAdminDao.java    License: 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("-------");
}