ApplicationContextAware使用实例

/****
 * SpringContext 上下文
 * 通过SpringContext获取Spring管理的业务Bean对象
 * 
 * @author 万文俊
 *
 */
public class SpringContextUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
      
    public static Object getBean(String name) throws BeansException {  
        return applicationContext.getBean(name);  
    }  

}
	<!-- 注入SpringContext 工具类 -->
	<bean id="springContextUtil" class="spring.fm.SpringContext"></bean>
	<!-- 测试获取数据 -->
	<bean id="student" class="spring.lei.Student">
		<property name="id" value="id89575"></property>
		<property name="name" value="zhou"></property>
		<property name="sex" value="男"></property>
	</bean>
public class Student {
	
	public Student(){
		System.out.println("Student实例化");
	}
	
	private String id;
	
	private String name;
	
	private String sex;
	
	private int age;
	
	public String toString(){
		return "student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
@Controller
public class Springcontroller {
	
	/***
	 * 返回类型是string需要用produces进行转码,并格式化
	 * json格式化 可以用Gson处理(obj <-> json)互相转换
	 * @return
	 * @date 2017年5月12日
	 * @author wanwenjun
	 */
	@RequestMapping(value="/stu",produces="application/json; charset=utf-8")
	@ResponseBody
	public String getStudent(){
		
		Student s = (Student) SpringContext.getBean("student");
		
		Gson gson = new Gson();
		
		//obj to String
		String stu = gson.toJson(s);
		
		//String to obj
		Student s2 = gson.fromJson(stu,Student.class);
		
		System.out.println(s2.toString());
		
		return stu;
	}
}

猜你喜欢

转载自whenjun.iteye.com/blog/2373902