1. 程式人生 > 實用技巧 >第一章、Spring概述

第一章、Spring概述

一、Spring概述

  1. Spring是一個開源框架
  2. Spring為簡化企業級開發而生,使用Spring,JavaBean就可以實現很多以前要靠EJB才能實現的功能。同樣的功能,在EJB中要通過繁瑣的配置和複雜的程式碼才能夠實現,而在Spring中卻非常的優雅和簡潔。
  3. Spring是一個IOC(DI)和AOP容器框架。
    • (IOC和AOP是程式設計思想,DI是IOC的具體實現方式)
  4. Spring的優良特性
    • 非侵入式:基於Spring開發的應用中的物件可以不依賴於Spring的API
    • 依賴注入:DI——Dependency Injection,反轉控制(IOC)最經典的實現。
    • 面向切面程式設計:Aspect Oriented Programming——AOP
    • 容器:Spring是一個容器,因為它包含並且管理應用物件的生命週期
    • 元件化:Spring實現了使用簡單的元件配置組合成一個複雜的應用。在 Spring 中可以使用XML和Java註解組合這些物件。
  5. 一站式:在IOC和AOP的基礎上可以整合各種企業應用的開源框架和優秀的第三方類庫(實際上Spring 自身也提供了表述層的SpringMVC和持久層的Spring JDBC)

二、搭建Spring執行時環境

2.1、新增依賴

       <dependency>
            <
groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</
artifactId> <version>4.3.12.RELEASE</version> </dependency>

2.2、在IDEA工具中通過如下步驟建立Spring的配置檔案

  • 在resources下建立application.xml檔案,作為spring的主配置檔案
  • 在IDEA建立配置檔案時沒有選項的解決辦法: https://www.cnblogs.com/jdy1022/p/13577616.html

2.3、入門程式

  目標:使用Spring建立物件,為屬性賦值

  1、建立Student類

public class Student {

    private String studentId;

    private String name;

    private String age;

    public Student(String studentId, String name, String age) {
        this.studentId = studentId;
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId='" + studentId + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

2、建立Spring配置檔案

<bean id="student" class="com.jdy.spring2020.bean.Student">
        <!--property中name的值要和pojo中屬性set方法會面的一致-->
        <property name="studentId" value="0001"/>
        <property name="name" value="jdy"/>
        <property name="age" value="18"/>
</bean>

3、測試:通過Spring的IOC容器建立Student類例項

@Test
    public void test_method01() {
        //1.建立IOC容器物件
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        //2.根據id值獲取bean例項物件
        Student student = (Student) context.getBean("student");
        System.out.println("student = " + student);

    }