组件注解符精简Spring配置文件

1.创建一个新的命名为lesson2,将lesson中的文件拷贝到lesson2中。
在这里插入图片描述
2.在SlayDragonQuest中添加组件注解符
在这里插入图片描述
3.在RescueDamselQuest中添加
在这里插入图片描述
4.修改BravekNight
在这里插入图片描述

@Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false

5.修改
在这里插入图片描述

spring项目无法引用@Resource注解
解决办法:Spring项目中缺少javax.annotation包的依赖。在maven配置文件pom.xml中加入依赖。

<!-- Javax Annotation -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>

6.创建配置文件
在这里插入图片描述

<?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.jyq.spring.lesson2" />
</beans>

7.创建测试类

package net.jyq.spring.lesson2;

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

public class Testknight {
        private ClassPathXmlApplicationContext context;
        @Before
        public void init() {
            // 基于Spring配置文件创建应用容器
            context = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
            // 提示用户
            System.out.println("Spring应用容器已创建。");
        }

        @Test
        public void testBraveKnight(){
            BravekNight knight= (BravekNight) context.getBean("Mike");
            knight.embarkOnQuest();
        }
        @Test
        public void testDamselRESCUINGknight(){
            DamselRescuingKnight knight= (DamselRescuingKnight) context.getBean("damselRescuingKnight");
            knight.embarkOnQuest();
        }

        @After
        public void destroy() {
            // 关闭应用容器
            context.close();
            // 提示用户
            System.out.println("Spring应用容器已关闭。");
        }
    }



运行结果
9.面向接口
9.1在lesson2中创建两个接口
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
9.2修改
在这里插入图片描述
在这里插入图片描述
9.3修改测试类
在这里插入图片描述
运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值