第一章、Spring概述

一、Spring概述

  1. Spring是一个开源框架
  2. Spring为简化企业级开发而生,使用Spring,JavaBean就可以实现很多以前要靠EJB才能实现的功能。同样的功能,在EJB中要通过繁琐的配置和复杂的代码才能够实现,而在Spring中却非常的优雅和简洁。
  3. Spring是一个IOC(DI)和AOP容器框架。控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)(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、添加依赖

         <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.2.2.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.0</version>
                <scope>provided</scope>
            </dependency>
            
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>

2.2、在IDEA工具中通过如下步骤创建Spring的配置文件

  •   在resources下创建application.xml文件,作为spring的主配置文件
  •   在IDEA创建配置文件时没有选项的解决办法: https://www.cnblogs.com/jdy1022/p/13577616.html

2.3、入门程序

  目标:使用Spring创建对象,为属性赋值

1、创建Student类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
    private String studentId;
    private String name;
    private String age;
}

关于lombok的知识参照:https://www.cnblogs.com/jdy1022/p/13969967.html

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类实例

public class Test_01 {

    ClassPathXmlApplicationContext context = null;
    {
        context = new ClassPathXmlApplicationContext("application_01.xml");
    }

    @Test
    public void test() {
        Student stu = context.getBean("stu", Student.class);
        System.out.println("stu = " + stu);
    }

}
原文地址:https://www.cnblogs.com/jdy1022/p/13677308.html