Spring微基础入门学习——使用注解(annotation)的方式依赖注入(DI)

前言

在以前的Spring学习中,相信大家使用最多、最早接触到的依赖注入方式,应该是使用applicationContext.xml文件进行配置。这是一种方法,但是如果你不喜欢使用XML,喜欢更加简洁的方法,那么Java注解自动装配bean一定是一个不二之选。

应用场景

一个声音系统,以CD和CD播放机为例,一张CD就是一个bean,CD机等待我们放入CD,然后开始播放音乐。

如何实现自动装配

1.组建扫描(componentScan):Spring会自动发现创建的bean
2.自动装配(autowiring):Spring自动满足bean之间的依赖

组建扫描和自动装配是实现的核心,可以将显示配置降到最低。

开始实现代码

接口:CompactDisc.java(CD)
package soundsystem;

public interface CompactDisc {
    void play();
}

使用注解@Component实例化一张CD,待会儿组建扫描就会自动扫描到这个Component,这就是无需显示配置bean的关键之处:
package soundsystem;

import org.springframework.stereotype.Component;
import soundsystem.CompactDisc;

@Component
public class SgtPeppers implements CompactDisc {

    private String title="Sgt.Pepper's Lonely Hearts Club Band";
    private String artist="The Beatles";


    public void play() {
        System.out.println("Playing " + title + " by " + artist);
    }
}

开启扫描组建,默认扫描当前包下的所有文件(soundsystem)
package soundsystem;

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

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

开启测试

使用Spring的test,测试CD的bean是否被注入。使用assertShouldNotBeNull即可,简单测试一下:
package soundsystem;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import soundsystem.CDPlayerConfig;
import soundsystem.CompactDisc;

import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull(){
        assertNotNull(cd);
    }

}

运行结果:

在这里插入图片描述
可以看到,CD的一个bean的确被注入了,断言显示为非空,说明基于注解的方式,也可以实现依赖注入。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值