Spring IOC
1, 概念解释:
依赖注入:每个对象负责管理与自己协作的对象(即它所依赖的对象)的引用,这将导致高度耦合和难以测试的代码。而依赖注入则是对象的依赖关系将由负责协调系统中各个对象的第三方组件在创建对象时设定。对象无需自行创建或管理它们的依赖关系——依赖关系将被自动注入到需要它们的对象中去。
2, 注入的方式:
1) 构造器注入。
例子:
a)接口一:Performer
package spring.di;
public interface Performer {
void performer() ;
}
b)实现接口的实现类:PoeticJuggler //会念诗的杂技人
package spring.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PoeticJuggler extends Juggler {
private Poem poem;
private int beanBags;
public PoeticJuggler(Poem poem) {
this.poem = poem;
}
public PoeticJuggler(int beanBags, Poem poem) {
this.beanBags = beanBags;
this.poem = poem;
}
@Override
public void performer() {
System.out.println("JUGGLING " + beanBags + " Beanbags");
System.out.println("While reciting...");
poem.recite();
}
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Performer performer = (Performer)ctx.getBean("Juggler");
performer.performer();
}
}
C)接口2:Poem
package spring.di;
public interface Poem {
void recite();
}
D)实现接口2的实现类:Sonnet29
package spring.di;
public class Sonnet29 implements Poem {
public void recite() {
// TODO Auto-generated method stub
System.out.println("hi!");
}
}
综上:
已经有了两个接口和实现了两个接口的实现类,然后需要做的下一步是把poem关联进PoeticJuggler里。这时可以用Spring的依赖注入。采用构造器注入的方式。
编写的bean.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="userService" class="tao.UserService"></bean> -->
<!-- <bean id="userServiceImpl" class="tao.UserServiceImpl"></bean> -->
<bean id="pom" class="spring.di.Sonnet29" />
<bean id="Juggler" class="spring.di.PoeticJuggler">
<constructor-arg value = "15"/>
<constructor-arg ref = "pom"/>
</bean>
</beans>
3, 关键点:
1) 面向接口编程和依赖注入,实现松耦合。这是编程的思路。
2) value和ref的区别:
value是指为简单类型复制,如:int,String等。
而ref属性是将ID为sonnet29的Bean引用(不是简单类型)传递给构造器。