第一步:集成Spring环境:
1.采用MyEclipse开发环境来搭建Spring框架是非常方便的,操作如下:
(如果自己搭建,可以引入Spring相应的jar包进来就可)
2.集成后的目录结构:
3.主要的是创建applicationContext.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.1.xsd">
</beans>
第二步,编写测试用例:
定义一个接口:
public interface Person {
public void speack();
}
定义两个实现类ChineseImpl和AmericanImpl:
public class ChineseImpl implements Person {
private String name;
private Integer age;
//提供name 和 age 属性的get和set方法
@Override
public void speack() {
System.out.println("----ChineseImpl---> name:" + name + ",age :" + age);
}
}
public class AmericanImpl implements Person {
private String name;
private Integer age;
//提供name 和 age 属性的get和set方法
@Override
public void speack() {
System.out.println("----AmericanImpl ---> name:" + name + ",age :" + age);
}
}
在application.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.1.xsd">
<!--每一个bean对应于一个对象,通过class指定类路径,通过id唯一区别,property属性来设置属性值 -->
<bean id="chinese" class="com.Model.ChineseImpl">
<property name="name" value="小明" />
<property name="age" value="20" />
</bean>
<bean id="american" class="com.Model.AmericanImpl">
<property name="name" value="Tom" />
<property name="age" value="40" />
</bean>
</beans>
第三步,测试
package com.Model;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
//通过getBean("id")来获取实例
Person person1 =(Person)context.getBean("chinese");
Person person2 =(Person)context.getBean("american");
person1.speack();
person2.speack();
}
}
结果:
—-ChineseImpl—> name:小明,age :20
—-AmericanImpl—> name:Tom,age :40