美文网首页
spring(三)-----核心API

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

作者: 探索的影子 | 来源:发表于2018-11-05 09:30 被阅读0次

目前掌握的知识开发出来的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

相关文章

网友评论

      本文标题:spring(三)-----核心API

      本文链接:https://www.haomeiwen.com/subject/oyujxqtx.html