Spring实例:Ioc依赖注入的一个例子
一.利用MyEclipse引入spring特性:
新建一个web项目后,右击项目名称,选择Myeclipse,选择add spring capabilities,选择所需的Libraries。
二.spring鼓励的面向接口编程:
Interface包里:
包含两个接口
1 package SSHinterface; 2 3 public interface Person { 4 public void useAxe(); 5 }
1 package SSHinterface; 2 3 public interface Axe { 4 public String chop() ; 5 }
Implement包里:
chinese实现了person、steelAxe和stoneAxe实现了Axe
package implement; import SSHinterface.Axe; import SSHinterface.Person; public class Chinses implements Person{ private Axe axe; public Chinses(){ } public void setAxe(Axe axe) { this.axe = axe; } public void useAxe() { // TODO Auto-generated method stub System.err.println(axe.chop()); } }
package implement; import SSHinterface.Axe; public class SteelAxe implements Axe{ public SteelAxe(){} public String chop() { // TODO Auto-generated method stub return "铁斧头比较快"; } }
package implement; import SSHinterface.Axe; public class StoneAxe implements Axe{ public StoneAxe(){} public String chop() { // TODO Auto-generated method stub return "用斧头砍树"; } }
spring提供的applicationContext.xml可以把各类bean组织起来:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 8 <!--spring会调用无参构造器进行实例,调用setter注射属性值,配置 chinses的实例,实现了implement.Chinses--> 9 <bean id="chinses" class="implement.Chinses"> 10 <!-- property标签:通过property接收,如果是个对象用ref,如果是个属性就用value --> 11 <!-- 此处将,steelAxe注入给axe属性 --> 12 <property name="axe" ref="steelAxe"></property> 13 </bean> 14 <bean id="stoneAxe" class="implement.StoneAxe"></bean> 15 <bean id="steelAxe" class="implement.SteelAxe"></bean> 16 17 </beans>
test类:
1 package SSHtest; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 import SSHinterface.Person; 7 8 import example.exampleBean; 9 10 public class SSHtest { 11 public static void main(String[] args) { 12 ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); 13 Person china = (Person) app.getBean("chinses");//根据xml的name来获取bean,相对于new Chinses,此处不需要在java代码里选择用什么样的斧头,因为在xml里进行了选择, 14 china.useAxe(); 15 } 16 }
控制台结果:
在xml里,选择了steelAxe注入在Axe中