Spring框架03:利用注解配置类取代Spring配置文件

上一讲,我们利用注解精简了XML配置文件,这一讲,我们准备利用注解配置类取代XML配置文件。
一、利用注解配置类取代Spring配置文件
1、在net.tjl.spring包里创建lesson03子包
在这里插入图片描述
2、创建Spring配置类来取代Spring配置文件
在这里插入图片描述

package net.tjl.spring.lesson03;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("net.tjl.spring.lesson03") //组件扫描表
public class AnnotationConfig {
    
    

}

3、创建测试类 - TestKnight
在这里插入图片描述

package net.tjl.spring.lesson03;

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

/**
 * 功能:测试骑士类
 * 作者:谭金兰
 * 日期:2021年03月17日
 */
public class TestKnight {
    
    
    private AnnotationConfigApplicationContext context;

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

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

    @Test
    public void testDamselRescuingKnight() {
    
    
        // 根据名称从应用容器里获取救美骑士对象
        DamselRescuingKnight damselRescuingKnight = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
        // 救美骑士执行任务
        damselRescuingKnight.embarkOnQuest();
    }

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

*运行测试类,查看结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/triet/article/details/114938398