天天看點

spring架構的概述以及spring中基于xml的ioc配置

1.spring的概述

什麼是spring?

Spring是一個開源的輕量級的應用程式開發架構,其目的是簡化企業的應用程式開發,降低侵入性,Spring提供的IOC和AOP功能,可以将元件之間的耦合度降到最低,便于後期的維護和更新,實作了軟體的高内聚低耦合思想。

Spring優勢?

友善解耦,簡化開發 ;AOP程式設計支援;聲明式事務的支援

友善程式的測試 ;友善內建各種優秀架構;降低JavaEE API的使用難度

2.spring中基于xml的ioc配置

使用IDEA編譯器,建立Maven工程後,配置pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.qlu</groupId>
    <artifactId>day01_qlu_03spring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>
    </dependencies>

</project>
           

xml的ioc配置:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd" >
<!--    把對象的建立交給spring來管理-->
    <bean id="userService" class="cn.qlu.service.impl.UserServiceImpl"></bean>

    <bean id="userDao" class="cn.qlu.dao.impl.UserDaoImpl"></bean>


</beans>
           

簡單測試:

public class Client {
    /**
     * 擷取spring 容器的Ioc核心容器,并根據id擷取對象
     * @param args
     */
    public static void main(String[] args) {
       //擷取核心容器  采用立即加載的方式 單例模式使用  BeanFactory是延時加載
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //根據id擷取對象
        UserService userService = (UserService) ac.getBean("userService");
        UserDao userDao =ac.getBean("userDao",UserDao.class);
        System.out.println(userService);
        System.out.println(userDao);

    }
}
           

Application Context 是 spring 中較進階的容器。和 BeanFactory 類似,它可以加載配置檔案中定義的 bean,将所有的 bean 集中在一起,當有請求的時候配置設定 bean。

最常被使用的 ApplicationContext 接口實作:

  • FileSystemXmlApplicationContext:該容器從 XML 檔案中加載已被定義的 bean。在這裡,你需要提供給構造器 XML 檔案的完整路徑。
  • ClassPathXmlApplicationContext:該容器從 XML 檔案中加載已被定義的 bean。在這裡,你不需要提供 XML 檔案的完整路徑,隻需正确配置 CLASSPATH 環境變量即可,因為,容器會從 CLASSPATH 中搜尋 bean 配置檔案。
  • WebXmlApplicationContext:該容器會在一個 web 應用程式的範圍内加載在 XML 檔案中已被定義的 bean。