当前位置: 代码迷 >> Web前端 >> java wev spring范例
  详细解决方案

java wev spring范例

热度:248   发布时间:2012-09-01 09:33:02.0
java wev spring实例
1.构建开发环境
2.在applicationContext.xml中添加bean配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	
	<bean id="helloWorld" class="com.demo.spring.HelloWorld">
		<property name="message"><value>China</value>  </property>
	</bean>
	
</beans>

3.bean类:HelloWorld.java
package com.demo.spring;

public class HelloWorld {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public String print(){
		return "Hello," + this.getMessage();
	}
}

4.测试类Test.java
package com.demo.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ApplicationContext ctx = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
		HelloWorld hello = (HelloWorld)ctx.getBean("helloWorld");
		System.out.println(hello.print());
	}

}

5.运行结果:
Hello,China



获取ApplicationContext的几种方式

第一种采用类路径的加载方式获取:

  

ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:application.xml");

ctx.getBean("xxxx");

此处的文件必须位于classpath路径中

第二种采用系统文件路径加载的方式获取:

ApplicationContext ctx=new FileSystemXmlApplicationContext("/application.xml");

此处的application.xml必须位于系统中一个具体的位置

第三种使用beanfactory加载配置信息:

   Resource r=new ClassPathResource(""); 此处必须为classpath路径中
        Resource res=new FileSystemResource("");必须为文件路径中
      
BeanFactory bf=new XmlBeanFactory(r);
  相关解决方案