通过自学的同时记录学习的点点滴滴,使用spring来托管.项目结构如下,lib是要导入的spring架包:

UserService类的代码:

package com.jason.services;

public class UserService {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void sayHello()
	{
		System.out.println("Hello "+name);
	}
}

 Test类的代码:

package com.jason.test;

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

import com.jason.services.UserService;

public class Test {

	private static ApplicationContext ac;

	public static void main(String[] args) {
		ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService us = (UserService) ac.getBean("userService");
		us.sayHello();
	}

}

 applicationContext.xml配置的代码:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:aop="http://www.springframework.org/schema/aop"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
 9     <bean id="userService" class="com.jason.services.UserService">
10       <property name="name">
11         <value>jason</value>
12       </property>
13     </bean>
14 </beans>

运行Test类,输出结果:

按照习惯的做法我们使用new 关键字创建对象,然后用该对象访问sayHello()方法,但是我们使用spring托管,框架帮我们做这些事情,这个简单的例子作为入门练习使用,真正spring的威力会在后面不断的总结学习。

 

posted on 2013-08-09 11:58  Jason_shang  阅读(388)  评论(0编辑  收藏  举报