Spring 4初级 2

来源:互联网 发布:淘宝群词荟萃 编辑:程序博客网 时间:2024/05/21 20:24

ioc 控制反转

链接文章解释的很好:http://blog.csdn.net/it_man/article/details/4402245


案例:一份java工作分配给张三李四其中一个,一个是通过生成对象。一个是通过bean来操作


代码:Test是接口,一个方法

public class JavaWork {    private Test tester;    public void setTester(Test tester) {        this.tester = tester;    }        public void test() {        tester.test();    }}
<bean id="zhangsan" class="com.cai.helloworld.ZhangSan"></bean>   <bean id="lisi" class="com.cai.helloworld.LiSi"></bean>    <bean id="javawork" class="com.cai.helloworld.JavaWork">    <property name="tester" ref="lisi"></property>    </bean>

测试方法:

public class Test {    public static void main(String[] args) {        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");        JavaWork jw=(JavaWork) ac.getBean("javawork");//        JavaWork jw=new JavaWork();//        jw.setTester(new ZhangSan());        jw.test();    }}
学了之后,ioc大致理解为,通过spring来实现对象的创立,通过xml文件的书写,来进行依赖注入。底层的方面参考链接。