spring:spring的核心API


1、BeanFactory接口

BeanFactory接口為Spring的原始接口,功能較為單一,其特點是,每次在獲得對象的時候才會創建對象,而ApplicationContext 是事先創建對象,需要的時候直接從容器中去即可。BeanFactory是一個工廠,用於生成任意bean。

 

2、ApplicationContext 類

(1)介紹:

每次容器創建的時候就會創建容器中所配置的對象,並且功能有很大的增強。但是,ApplicationContext較為浪費資源,因為它將所有的對象一次全部創建出來,而BeanFactory是在調用和對象的時候才會去創建對象。

(2)ApplicationContext 獲取配置文件的方法:

從類路徑下獲取配置文件:

 ApplicationContext applicationContext=new
                ClassPathXmlApplicationContext("applicationContext.xml");//創建容器對象

從硬件絕對路徑下獲取配置文件(指定盤符下的xml):

FileSystemXmlApplicationContext("路徑")

 

3、ApplicationContext 類與BeanFactory接口的對比

(1)ApplicationContext 類:

StudentServiceImpl:
public class StudentServiceImpl {
    private StudentDao studentDao;

    public StudentServiceImpl() {
        System.out.println("service的實現類被創建了!!");
    }

    public StudentDao getStudentDao() {
        return studentDao;
    }
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    public void addStudent(){
        System.out.println("StudentService的實現類的Add方法!!");
        studentDao.addStudent();
    }
}

測試類:

  public static void main(String[] args) {
        ApplicationContext applicationContext=new
                ClassPathXmlApplicationContext("applicationContext.xml");//創建容器對象
        StudentServiceImpl studentService=(StudentServiceImpl) applicationContext.getBean("studentService");
        studentService.addStudent();
    }

測試結果:

service的實現類被創建了!!
StudentService的實現類的Add方法!!
StudentDao的實現類的Add方法!!

 

(2)BeanFactory接口

   public static void main(String[] args) {
        BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        StudentServiceImpl studentService=(StudentServiceImpl) beanFactory.getBean("studentService");
        studentService.addStudent();
    }
  • 在調用getBean的時候才會去創建對象
  • Bean 工廠是工廠模式的一個實現,提供了控制反轉功能,用來把應用的配置和依賴從應用代碼中分離。最常用的BeanFactory 實現是XmlBeanFactory (org.springframework.beans.factory.xml.XmlBeanFactory類)類。它根據 XML 文件中的定義加載beans。該容器從XML 文件讀取配置元數據並用它去創建一個完全配置的系統或應用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM