本实例主要记录在java project中配置spring最基本的使用
1.下载spring,本实例用的是最新版4.3.3
spring 官网下载,下载地址:http://repo.spring.io/release/org/springframework/spring/
2.创建java project, 项目名Spring_01
3.引入所需jar文件,导入spring-framework-4.3.3.RELEASE-dist\spring-framework-4.3.3.RELEASE\libs下所有jar, 还有commons-logging-1.1.3.jar(在struts下载包中,否则会报错)
4.创建一个动物interface, 取名叫Animal
package com.bobo.app;
public interface Animal {
public void call();
public void walk();
}
5.创建Dog class, 实现Animal接口,并实现接口中的两个方法
package com.bobo.app;
public class Dog implements Animal {
@Override
public void call() {
System.out.println("汪汪叫");
}
@Override
public void walk() {
System.out.println("四条腿走路");
}
}
6.创建Duck class, 实现Animal接口,并实现接口中的两个方法
package com.bobo.app;
public class Duck implements Animal {
@Override
public void call() {
System.out.println("呱呱叫");
}
@Override
public void walk() {
System.out.println("两条腿走路");
}
}
7.在src下创建spring配置文件applicationContext.xml, 配置两个bean
<?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:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm.xsd">
<bean id="duckBean" class="com.bobo.app.Duck"> </bean>
<bean id="dogBean" class="com.bobo.app.Dog"> </bean>
</beans>
8.创建测试类Test
package com.bobo.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Dog dog = (Dog) ac.getBean("dogBean");
Duck duck = (Duck) ac.getBean("duckBean");
dog.call();
dog.walk();
duck.call();
duck.walk();
}
}
9.测试结果
汪汪叫
四条腿走路
呱呱叫
两条腿走路
10.本实例源码,点击下载