spring學習之IOC容器

IOC容器

IOC容器,有時候也稱爲依賴注入(DI)。經過對象本身定義的依賴項,在建立bean的時候,再把這些依賴項注入進來。這個過程,跟咱們正常的設計是相反的,咱們正常是在對象裏new一個對象,是咱們的程序控制管理對象,而在spring裏,是經過容器來建立對象的,由容器來控制的。在基於spring的應用中,IOC容器基於配置元數據,實例化、配置、組裝對象,並管理這些對象的整個生命週期。
配置元數據的讀取,能夠經過XML文件、註解等方式,能夠用的上下文有ClassPathXmlApplicationContext、AnnotationConfigApplicationContext等。BeanFactory和ApplicationContext是比較經常使用的類,正常狀況下,咱們用ApplicationContext,ApplicationContext繼承了BeanFactory,包含了BeanFactory的全部功能。
在基於spring的應用中,IOC容器管理的對象,稱之爲bean。每一個應用是由多個bean組成的,bean之間的依賴關係由容器來管理。java

容器的實例化與使用

元數據的配置,用來告訴Spring容器如何實例化、配置和組裝應用程序中的對象。
XML配置文件時,用bean標籤來配置元數據。註解下用@bean、@Configuration等來配置元數據。spring

XML配置

配置文件daos.xmlapp

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--id是bean的惟一標識,class是bean的全類名-->
    <bean id="orderDao" class="com.learn.ch1.OrderDao"/>

</beans>

配置文件services.xml測試

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="orderService" class="com.learn.ch1.OrderService"/>

</beans>

測試代碼spa

@Test
public void test() {
    //這邊能夠直接引入多個xml配置文件,也能夠引入一個,而後在這個xml裏用<import resource="XXX.xml"/>標籤引入其餘配置文件。
    //XML用的ApplicationContext是ClassPathXmlApplicationContext
    ApplicationContext app = new ClassPathXmlApplicationContext("services.xml","daos.xml");
    String[] names = app.getBeanDefinitionNames();
    for (String name : names) {
        System.out.println(name);
    }
}

另外兩個java類就不寫了,運行結果以下:
image.png設計

註解

MyConfigcode

@Configuration
public class MyConfig {
    @Bean
    public OrderDao orderDao() {
        return new OrderDao();
    }

    @Bean
    public OrderService orderService() {
        return new OrderService();
    }
}

測試代碼xml

@Test
public void test() {
    //註解下用的ApplicationContext是AnnotationConfigApplicationContext
    ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
    String[] names = app.getBeanDefinitionNames();
    for (String name : names) {
        System.out.println(name);
    }
}

運行結果以下:
image.png對象

XML和註解

從上面兩個例子能夠看出,註解下的配置,更短更簡潔,但不是說註解的方式更好。
XML也是有優勢的:blog

  1. XML能夠在不編譯代碼的狀況下直接接入鏈接組件。
  2. 配置集中,好控制。
相關文章
相關標籤/搜索