一、环境准备:
1、spring-framework-4.3.18.RELEASE
2、jdk 1.7
3、commons-logging-1.2.jar
spring与common-logging官方架包下载可参考我的另一篇文章:三大框架官方架包下载方法
二、开始搭建:
1、创建java项目:
2、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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="chinese" class="com.test.inter.impl.Chinese">
<property name="axe" ref="stoneAxe" />
</bean>
<bean id="stoneAxe" class="com.test.inter.impl.StoneAxe" />
<bean id="win" class="javax.swing.JFrame" />
<bean id="date" class="java.util.Date" />
</beans>
3、Axe.java
package com.test.inter;
public interface Axe {
public String chop();
}
4、StoneAxe.java
package com.test.inter.impl;
import com.test.inter.Axe;
public class StoneAxe implements Axe {
@Override
public String chop() {
return "斧头砍柴好慢";
}
}
5、Person.java
package com.test.inter;
public interface Person {
public void useAxe();
}
6、Chinese.java
package com.test.inter.impl;
import com.test.inter.Axe;
import com.test.inter.Person;
public class Chinese implements Person {
private Axe axe;
@Override
public void useAxe() {
System.out.println("我打算去砍点柴");
System.out.println(axe.chop());
}
public void setAxe(Axe axe) {
this.axe = axe;
}
}
7、TestSpring.java
package com.test.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.inter.Person;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Person p = ctx.getBean("chinese", Person.class);
p.useAxe();
}
}