Spring利用DI技术管理对象之间的依赖。
IoC : Inversion of Control(控制反转)
DI :Dependency Injection(依赖注入)
一、模拟Spring的原理,利用配置文件来决定反射实现某个类的实例。
1、新建config.properties文件
blue=cn.zxb.spring.BlueDuckImpl
yellow=cn.zxb.spring.YellowDuckImpl
2、新建接口Duck和实现类
package cn.zxb.spring;
public interface Duck {
public void say();
}
package cn.zxb.spring;
public class BlueDuckImpl implements Duck {
public void say() {
System.out.println("I am BlueDuck!");
}
}
3、测试主类,通过读取配置文件中指定key值的value来具体实例化指定类的对象
package cn.zxb.spring;
import java.util.ResourceBundle;
public class MainTest {
public static void main(String[] args) throws Exception {
ResourceBundle bundle = ResourceBundle.getBundle("config");
String blue = bundle.getString("blue");
Duck duck = (Duck)Class.forName(blue).newInstance();
duck.say();
}
}
输出结果为
I am BlueDuck!
二、使用Spring的IoC
1、写一个配置的xml文件 applicationContext.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-3.0.xsd">
<bean id="blueDuck" class="cn.zxb.spring.Ioc1.BlueDuckImpl"/>
<bean id="yellowDuck" class="cn.zxb.spring.Ioc1.YellowDuckImpl"/>
</beans>
2、读取xm的配置进行实例化
package cn.zxb.spring.Ioc2;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.zxb.spring.Ioc1.Duck;
public class MainTest {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("cn/zxb/spring/Ioc2/applicationContext.xml");
Duck duck = (Duck)factory.getBean("blueDuck");
duck.say();
}
}
输出结果为:I am BlueDuck!
三、单例和多例
1、配置scope="singleton"为单例,Spring默认是单例的,prototype为多例。
四、BeanFactoryAware接口
private BeanFactory factory = null;
public void setBeanFactory(BeanFactory factory) throws BeanException{
this.factory = factory;
}
五、自动注入
<bean id="userAction" class="cn.zxb.UserAction" scope="singleton" autowire="byType"/>
<bean id="userAction" class="cn.zxb.UserAction" scope="singleton" autowire="byName"/>
六、注解注入
<context:annotation-config/>
七、组件扫描
<context:component-scan base-package="cn.zxb"/>