1、开发工具 Myeclipse
2、步骤
(1)新建Java项目
(2)右键点击项目->MyEclipse->Add Spring Capabilities,选择对应的Spring版本号和需要导入的Spring jar包。
(3)新建类HellWorld.java和测试的Test.java,修改配置文件名为beans.xml(文件名称可自定义,个人习惯修改为beans.xml)。
(4)HelloWorld.java如下:
package com.spring.bean;
public class HelloWorld {
private String name;
public void show(){
System.out.println("Spring,hello,"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(5)beans.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="hellobean" class="com.spring.bean.HelloWorld">
<property name="name" value="jeff"></property>
</bean>
</beans>
其中:id为自定义的bean标识名称,唯一,class是和id对应的类全名,property可以该类中的属性进行配置赋值。 (6)测试
package com.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.bean.HelloWorld;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext content =
new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) content.getBean("hellobean");
obj.show();
}
}
三行代码的意思分别是: 读取配置文件beans.xml 获取bean的idhellobean并返回,转换为HelloWorld类型