spring(三)-----核心API

目前掌握的知识开发出来的spring项目和ssm三大框架整合起来的项目差距还是很大。这一部分就目前来说还是很重要,但是到后面就不再使用了。所以看个人的取舍吧。
这是核心api图


20180524095322510.png

在这里面我们需要重点了解的是BeanFactory,ApplicationContext,FileSystemApplicationContext,ClassPathXmlApplicationContext

BeanFactory

高端的后面教程再说,简单点来说它就是一个工厂,用于生成任意bean的。
特点:采用的是延迟加载,也就是第一次getBean的时候才会初始化对象。

ApplicationContext

是beanFactory子接口,功能更加强大
特点:

  • 国际化处理
  • 事件传递
  • Bean自动装配
  • 不同应用层的context实现

ClassPathXmlApplicationContext

用于加载classpath(类路径,src)下指定的xml
web路径:/web-inf/classes/.....xml

FileSystemXmlApplicationContext

用于加载系统盘符下的指定xml
通过java webServletContext.getRealPath() 获得具体盘符。
web路径:/web-inf/.....xml

实践才是检验真理的唯一标准

为了证明BeanFactorys是延迟加载,ApplicationContext不是我写了连个小例子来证明一下。
UserService和它的实现类

public interface UserService {
    void addUser();
}


public class UserServiceImpl implements UserService {
    public UserServiceImpl() {
        System.out.println("UserServiceImpl.UserServiceImpl");
    }

    @Override
    public void addUser() {
        System.out.println("UserServiceImpl.addUser");
    }
}

BookService


public interface FoodService {
    public void getFood();
}

public class FoodServiceImpl implements FoodService {

    @Override
    public void getFood() {
        System.out.println("FoodServiceImpl.getFood");
    }

    public FoodServiceImpl() {
        System.out.println("FoodServiceImpl.FoodServiceImpl");
    }
}

测试类UserServiceImplTest(貌似命名没有命标准)



public class UserServiceImplTest {



    @Test
    public void addUserByIOC() {
        String applicationContextPath = "com/spring/helloworld/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(applicationContextPath);
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.addUser();
    }

    @Test
    public void addUserByIOC2() {
        String applicationContextPath = "com/spring/helloworld/applicationContext.xml";
        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(applicationContextPath));
        UserService userService = (UserService) beanFactory.getBean("userService");
        userService.addUser();
    }
}

第一个采用applicationContext,第二个采用beanFactory结果看下图:
image.png

我把构造函数里面加了测试输出这样就会比较直观的表现出来beanFactory并没初始化FoodService

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容