1.2初探Spring——利用注解配置类取代Spring配置文件

一、课程引入

  • 上一讲,我们利用注解精简了XML配置文件,这一讲,我们准备利用注解配置类取代XML配置文件。

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

(一)打开项目

  • Maven项目 - SpringDemo
    在这里插入图片描述

(二)创建新包

  • net.huawei.spring包创建day03子包
    在这里插入图片描述

(三)拷贝类与接口

  • day02子包的类与接口拷贝到day03子包
    在这里插入图片描述

(四)创建注解配置类

  • day03子包里创建SpringConfig类,取代Spring配置文件
    在这里插入图片描述
package net.ls.spring.day03;

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

/**
 * 功能:注解类配置
 * 作者:ls
 * 日期:2023年02月20日19时12分09秒
 */
@Configuration//表明是spring配置类
@ComponentScan("net.ls.spring.day03")
public class SpringConfig {

}

  • 注解@Configuration声明当前类是一个配置类,对应一个Spring配置文件,可以取而代之。
  • 注解@ComponentScan自动扫描包名下所有使用@Component@Service@Repository@Mapper@Controller的类,并注册为Bean
  • 注解@ComponentScan("net.huawei.spring.day03")相当于Spring配置文件里的
    <context:component-scan base-package="net.huawei.spring.day03"/>

(五)创建测试类

  • test/java里创建net.huawei.spring.day03包,在包里创建TestKnight
    在这里插入图片描述
  • AnnotationConfigApplicationContext ⟹ \Longrightarrow⟹ApplicationContext⟹ \Longrightarrow⟹BeanFactory
    在这里插入图片描述
package net.ls.spring.day03;

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

import java.lang.annotation.Annotation;

/**
 * 功能:测试骑士类
 * 作者:ls
 * 日期:2023年02月20日19时19分57秒
 */
public class TestKnight {
        private AnnotationConfigApplicationContext context; // 基于注解配置类的应用容器

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

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

            // 根据名称从应用容器里获取救美骑士对象
            Knight knight2 = (Knight) context.getBean("rescueDamselknight");
            // 救美骑士执行任务
            knight2.embarkOnQuest();
        }

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

}

(六)运行测试类

  • 运行testKnight测试方法,查看结果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值