首页 > 代码库 > spring4.0.0的配置和使用
spring4.0.0的配置和使用
1.创建一个javaproject或者webproject,我创建的时webproject,编译器用的时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測试结果输出:
中国人非常会吃!
中国人健步如飞!
美国人吃西餐!
美国人常常坐车!
spring4.0.0的配置和使用