Spring初探(一)

  • Spring框架是一个轻量级的企业级开发的一站式解决方案,用于解决基于JavaEE开发的所有问题。Spring框架主要提供了IoC容器、AOP、数据访问、Web开发等相关技术的支持。
  • 此次课我们主要学习的就是IcO——控制反转:以前是由用户来创建对象,而IcO就是让Spring容器去创建Bean对象。
一、创建项目

这里我们先创建一个名为SpringDemo2021的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>net.hlw.spring</groupId>
    <artifactId>SpringDemo2021</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- spring.version -->
        <spring.version>5.3.4</spring.version>
    </properties>

    <dependencies>
        <!--Spring核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring Bean-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


三、创建杀龙任务类:SlayDragonQuest和勇敢骑士类:BraveKnight
package net.hlw.spring.lesson01;

public class SlayDragonQuest {
    public void embark(){
        System.out.println("执行杀龙任务");
    }
}

package net.hlw.spring.lesson01;

public class BraveKnight {
    private SlayDragonQuest slayDragonQuest;

    public void setSlayDragonQuest(SlayDragonQuest slayDragonQuest) {
        this.slayDragonQuest = slayDragonQuest;
    }

    public void embarkOnQuest(){
        slayDragonQuest.embark();
    }
}


四、采用Spring框架让勇敢骑士完成杀龙任务

1、在resources目录里创建log4.properties文件。

log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n


2、在resources目录中创建xmlconfig目录,再在里面创建spring-config.xml文件。在右上角点击Configure application context,在下拉选项中点击Create new application context…,内容不用更改,点击OK即可
3、在Spring配置文件里创建Bean。

<bean id="slayDragonQuest" class="net.hlw.spring.lesson01.SlayDragonQuest"/>
        <bean id="Mike" class="net.lxt.spring.lesson01.BraveKnight">
            <property name="slayDragonQuest" ref="slayDragonQuest"/>
        </bean>

4、创建测试类:TestBraveKnightNew

package net.hlw.spring.lesson01;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBraveKnightNew {
    private ClassPathXmlApplicationContext context;//基于类路径XML配置文件的应用容器
    @Before
    public void init(){
        //基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("xmlconfig/spring-config01.xml");
        //提示用户
        System.out.println("Spring应用容器已创建");
    }

    @Test
    public void testBraveKnight(){
        //根据名称从应用容器里获取勇敢骑士对象
        BraveKnight braveKnight = (BraveKnight)context.getBean("Mike");
        //勇敢骑士执行任务
        braveKnight.embarkOnQuest();

        BraveKnight knight1 = (BraveKnight)context.getBean("knight1");
        knight1.embarkOnQuest();

        BraveKnight knight2 = (BraveKnight)context.getBean("knight1");
        knight2.embarkOnQuest();
    }
    @After
    public void destory(){
        //关闭应用容器
        context.close();
        //提示
        System.out.println("Spring应用容器已关闭");
    }
}


测试结果:
在这里插入图片描述

5、基于一个类可以创建多个对象,因此,在spring-config.xml文件里,也可以基于同一个类创建多个Bean,但同一个Bean不能重复定义。
在这里插入图片描述

五、采用构造函数注入方式给Bean注入属性

1、创建救美任务类 :RescueDamselQuest

package net.hlw.spring.lesson01;
public class RescueDamselQuest {
    public void embark(){
        System.out.println("执行救美任务");
    }
}

2、创建救美骑士类:DamselRescuingKnight

package net.hlw.spring.lesson01;

public class DamselRescuingKnight {
    private RescueDamselQuest rescueDamselQuest;

    public DamselRescuingKnight(RescueDamselQuest rescueDamselQuest) {
        this.rescueDamselQuest = rescueDamselQuest;
    }
    public void embarkOnQuest(){
        rescueDamselQuest.embark();
    }
}


3、在Spring配置文件里创建救美骑士Bean
在这里插入图片描述

4、创建测试类TestDamselRescuingKnightNew

package net.hlw.spring.lesson01;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDamselRescuingKnightNew {
    private ClassPathXmlApplicationContext context;//基于类路径XML配置文件的应用容器
    @Before
    public void init(){
        //基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("xmlconfig/spring-config01.xml");
        //提示用户
        System.out.println("Spring应用容器已创建");
    }

    @Test
    public void testDamselRescuingKnight(){
        //根据名称从应用容器里获取救美骑士对象
        DamselRescuingKnight damselRescuingKnight = (DamselRescuingKnight)context.getBean("damselRescuingKnight");
        //救美骑士执行任务
        damselRescuingKnight.embarkOnQuest();
    }
    @After
    public void destroy(){
        //关闭应用容器
        context.close();
        //提示
        System.out.println("Spring应用容器已关闭");
    }
}


测试结果:
在这里插入图片描述

六、多个Spring配置文件

如果有多个类创建Bean,采用XML配置方法会让Spring配置文件很臃肿,所以可以将其拆分为多个Spring配置文件。
1、拆分Spring配置文件
在这里插入图片描述

2、创建测试骑士类

package net.hlw.spring.lesson01;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestKnight {
    private ClassPathXmlApplicationContext context;//基于类路径XML配置文件的应用容器
    @Before
    public void init(){
        //基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("xmlconfig/spring-config*.xml");
        //提示用户
        System.out.println("Spring应用容器已创建");
    }

    @Test
    public void testKnight(){
        //根据名称从应用容器里获取对象
        BraveKnight mike = (BraveKnight)context.getBean("Mike");
        BraveKnight knight1= (BraveKnight)context.getBean("knight1");
        BraveKnight knight2= (BraveKnight)context.getBean("knight2");
        DamselRescuingKnight damselRescuingKnight = (DamselRescuingKnight)context.getBean("damselRescuingKnight");
        //让骑士们执行任务
        mike.embarkOnQuest();
        knight1.embarkOnQuest();
        knight2.embarkOnQuest();
        damselRescuingKnight.embarkOnQuest();
    }
    @After
    public void destory(){
        //关闭应用容器
        context.close();
        //提示
        System.out.println("Spring应用容器已关闭");
    }
}


测试结果:
在这里插入图片描述

七、使用组件注解符精简Spring配置文件
  • 首先创建net.lxt.spring.lesson02的包,再将lesson01的四个类拷贝到lesson02的包中。

  • 修改SlayDragonQuest、RescueDamselQuest、BraveKnight、DanselRescuingKnight为他们添加组件注解符:@Component.
    且为BraveKnight的组件注解符设置参数:Mike。
    给BraveKnight和DanselRescuingKnight添加主动装配注解符:@Autowired/@Resource/@Inject

在这里插入图片描述

  • 注意:是要删除BraveKnight类的setSlayDragonQuest()方法和DanselRescuingKnight类的构造方法,因为已经通过自动装配注解设置了勇敢骑士的杀龙任务属性。
    在这里插入图片描述
    3、在resources目录创建xml_annotation子目录,然后在里面创建Spring配置文件: spring-config.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--组件扫描,扫描指定包下添加了朱姐的类或接口,将其生成Bean对象-->
    <context:component-scan base-package="net.hlw.spring.lesson02"/>
</beans>

4、在test/java里创建net.hw.spring.lesson2包,在包里创建TestKnight类

 private ClassPathXmlApplicationContext context;//基于类路径XML配置文件的应用容器

    @Before
    public void init(){
        //基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("xml_annotation/spring_config.xml");
    }

    @Test
    public void testBraveKnight(){
        //根据名称从应用容器里获取勇敢骑士对象
        Knight knight1 = (Knight) context.getBean("Mike");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @Test
    public void testDamselRescuingKnight(){
        Knight knight1 = (Knight) context.getBean("damselRescuingKnight");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @After
    public void destory(){
        //关闭应用容器
        context.close();
    }

测试结果:
在这里插入图片描述

八、程序优化,面向接口

1、创建任务接口 - Quest和创建骑士接口 - Knight
在这里插入图片描述
2、修改杀龙任务类 - SlayDragonQuest、救美任务类 - RescueDamselQuest、勇敢骑士类 - BraveKnight、救美骑士类 - DamselRescuingKnight。
在这里插入图片描述
在这里插入图片描述
3、修改测试类

package net.hlw.spring.lesson02;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestKnight {
    private ClassPathXmlApplicationContext context;//基于类路径XML配置文件的应用容器

    @Before
    public void init(){
        //基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("xml_annotation/spring_config.xml");
    }

    @Test
    public void testBraveKnight(){
        //根据名称从应用容器里获取勇敢骑士对象
        Knight knight1 = (Knight) context.getBean("Mike");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @Test
    public void testDamselRescuingKnight(){
        Knight knight1 = (Knight) context.getBean("damselRescuingKnight");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @After
    public void destory(){
        //关闭应用容器
        context.close();
    }
}

测试结果:
在这里插入图片描述

课堂练习

任务1、两种骑士交换执行任务。
要求勇敢骑士去救美,要求救美骑士去杀龙。
在这里插入图片描述
在这里插入图片描述
任务2、两种骑士都执行两项任务。
要求勇敢骑士先执行杀龙任务,再执行救美任务。
在这里插入图片描述
要求救美骑士先执行救美任务,再执行杀龙任务。
在这里插入图片描述
任务3、两种骑士再交换执行任务。
要求勇敢骑士完成杀龙任务,救美骑士完成救美任务。
在这里插入图片描述

Ⅰ、利用注解配置类取代Spring配置文件

1、在net.hw.spring包里创建lesson03子包,并将lesson02子包的类与接口拷贝到lesson03子包。
2、在net.hw.spring.lesson03包里创建AnnotationConfig类来取代Spring配置文件
在这里插入图片描述
3、在test/java里创建net.hw.spring.lesson03包,在包里创建TestKnight

package net.hlw.spring.lesson03;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestKnight {
    private AnnotationConfigApplicationContext context;//基于注解类的应用容器

    @Before
    public void init(){
        //基于注解配置类创建应用容器
        context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
    }

    @Test
    public void testBraveKnight(){
        //根据名称从应用容器里获取勇敢骑士对象
        Knight knight1 = (BraveKnight) context.getBean("Mike");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @Test
    public void testDamselRescuingKnight(){
        Knight knight1 = (Knight) context.getBean("damselRescuingKnight");
        //勇敢骑士执行任务
        knight1.embarkOnQuest();
    }
    @After
    public void destory(){
        //关闭应用容器
        context.close();
    }
}


测试结果:在这里插入图片描述

Ⅱ、采用Java配置类管理Bean

1、在net.hw.spring包里创建lesson04子包,并在lesson04子包里创建杀龙任务类 - SlayDragonQuest、勇敢骑士类 - BraveKnight。
注意:没有添加@Component注解符声明Bean;没有使用@Autowired注解符注入Bean。
2、在lesson04子包里创建Spring配置类 - SpringConfig。
在这里插入图片描述
3、在/test/java里创建net.hw.spring.lesson04包,在包里创建TestKnight。

package net.hlw.spring.lesson04;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestKnight {

    private AnnotationConfigApplicationContext context; // 基于注解配置类的应用容器

    @Before
    public void init() {
        // 基于注解配置类创建应用容器
        context = new AnnotationConfigApplicationContext(SpringConfig.class);
    }

    @Test
    public void testBraveKnight() {
        // 根据名称从应用容器里获取勇敢骑士对象
        BraveKnight knight = (BraveKnight) context.getBean("Mike");
        // 勇敢骑士执行任务
        knight.embarkOnQuest();
    }

    @After
    public void destroy() {
        // 关闭应用容器
        context.close();
    }
}


测试结果:在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值