首页 > 代码库 > spring4.0.0的配置和使用
spring4.0.0的配置和使用
1.创建一个java工程或者web工程,我创建的时web工程,编译器用的时myeclipse2013
2.在lib目录下面倒入spring需要的一些核心包如下
还需在lib目录下面导入数据库的驱动包,如果要做web开发,则还需把驱动包导入到buiderpath里面,否则可能会出现找不驱动包
3.在src目录下面编写spring的配置文件appliactionContext.xml文件,applicationContext.xml文件的格式在spring的官方文档里面有,我的配置文件如下:
<?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.xsd">
<!--
<bean id="..." class="...">
collaborators and configuration for this bean go here
</bean>
<bean id="..." class="...">
collaborators and configuration for this bean go here
</bean>
more bean definitions go here -->
<bean id="chinese" class="com.iface.Chinese">
</bean>
<bean id="american" class="com.iface.American">
</bean>
</beans>
4.编写测试类
1,编写接口;
package com.face;
public interface Human {
public void eat();
public void walk();
}
2,实现类
package com.iface;
import com.face.Human;
public class American implements Human{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("美国人吃西餐!");
}
@Override
public void walk() {
// TODO Auto-generated method stub
System.out.println("美国人经常坐车!");
}
}
package com.iface;
import com.face.Human;
public class Chinese implements Human{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("中国人很会吃!");
}
@Override
public void walk() {
// TODO Auto-generated method stub
System.out.println("中国人健步如飞!");
}
}
3,写工厂类
package com.factory;
import com.face.Human;
import com.iface.American;
import com.iface.Chinese;
public class Factory {
public Human getHuman(String name){
if("Chinese".equals(name)){
return new Chinese();
}else if("American".equals(name)){
return new American();
}else{
return null;
}
}
}
5,编写测试类
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.face.Human;
public class TestMain1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new FileSystemXmlApplicationContext("src/applicationContext.xml");
Human human=null;
human=(Human) context.getBean("chinese");
human.eat();
human.walk();
human=(Human) context.getBean("american");
human.eat();
human.walk();
}
}
6测试结果输出:
中国人很会吃!
中国人健步如飞!
美国人吃西餐!
美国人经常坐车!