为什么实际功能类,如Person类,要把接口定义为一个属性,而且如果在一个包里面就不需要Import吗?

 

将接口定义为属性就可以 直接调用这个接口,  由于接口中有抽象方法, 爱屋及乌,就可以直接调用接口中的 方法,而不需要考虑实现类.

没有实现类是不行的,只不过将实现类的导入放到了  xml 的bean的 property中 ref 引入.

 

这样在一个功能类的内部,就只需要调用接口编程.

只不过,最后在Main 的内部,要引入Spring组件,读取xml文件,

package com.jike.spring.chapter01;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;


public class MainOne {

    public static void main(String[] args) {
        Resource r = new FileSystemResource("helloMessage.xml");//读取xml配置文件
        BeanFactory f = new XmlBeanFactory(r);           //用XmlBeanFactory来加载配置文件,启动IOC容器  //需要配置文件启动容器
        Person person = (Person)f.getBean("person");        //从IOC容器中获取Person类的实例.          // 创建person的实例吗???
        String s = person.sayHello();                //用person实例来输出
        System.out.println("The person is currently saying"+s);
    }

}

 

posted on 2016-07-18 22:17  雪的心  阅读(525)  评论(0编辑  收藏  举报

导航