一、概念

优点:
(1)控制反转(IOC)和面向切面编程(AOP)
(2)开源、免费、轻量级、非侵入式(即不破坏原有代码
(3)支持事物处理、对框架整合的支持

核心部分
(1)IOC:控制反转,把创建对象过程交给Spring进行管理
(2)AOP:面向切面,不修改源代码进行功能增强

Spring特点
(1)方便解耦,简化开发
(2)AOP编程支持
(3)方便程序测试
(4)方便和其他框架进行整合
(5)方便进行事务操作
(6)降低API难度

Spring5框架
image.png

二、HelloSpring

(1)创建maven项目,导入jar包,创建hello类

  <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

(2)在resources文件下新建ApplicationContext.xml (spring给对象实例赋值的实质是调用set方法)

<?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">

    <bean id="hello" class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

(3)在测试包下新建MyTest测试类,在主函数下新建对象context,通过context来调用对象

   public static void main(String[] args) {
        //加载Spring配置文件,获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //获取bean对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }

noti9j6s
1 声望0 粉丝