Spring微基础入门学习——使用JavaConfig显示配置bean

前言

在前文(https://blog.csdn.net/qq_43576028/article/details/104714918)中,我们学习了基于注解(Annotation)的方式去配置bean,自动配置有2个核心组成部分:
1.ComponentScan——组建扫描
2.Autowired——自动装配
接下来介绍Spring装配bean的另一种方式——基于JavaConfig的显示装配。

为什么

既然有了这么方便的自动装配bean的方式,为什么还要用JavaConfig呢。这是因为有时候,项目中的组建是来自第三方库的,在这种情况下是没有办法在类上添加@Component和@Autowired注解的,所以需要JavaConfig

前期准备

以声音系统(Sound System)为例,我们创建一个CD类接口、CD播放机类接口、继承CD接口实例化一张唱片、继承CD播放机类接口实例化一台CD播放机,然后检测能否达到依赖注入(DI)的效果。

CD类接口:CompactDisc.java

package soundsystem;

public interface CompactDisc {
    void play();
}

CD播放器类接口:MediaPlayer.java

package soundsystem;

public interface MediaPlayer {
    void play();
}

实例化一张CD:彭羚——《如梦初醒》SgtPeppers.java

package soundsystem;

public class SgtPeppers implements CompactDisc {

    private String title="入门初醒";
    private String artist="彭羚";

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

实例化一台CD播放机:CDplayer.java,利用@AutoWired自动装配一张cd

package soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MediaPlayer {
    private CompactDisc cd;
    
    @Autowired()
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }

    public void play() {
        cd.play();
    }
}

显示配置JavaConfig

对CD播放器进行配置,编写CDPlayerConfig.java,使用@Bean对刚才的那张唱片进行显示配置,这里的bean会自动返回一张唱片。事实上,不一定要返回彭羚的《如梦初醒》,我们可以自己把握,根据自己的喜好决定返回哪张唱片,甚至随机返回。

package soundsystem;

import org.springframework.context.annotation.Bean;

public class CDPlayerConfig {
    @Bean
    public CompactDisc sgtPeppers(){
        return new SgtPeppers();
    }
}

测试

利用Sping的测试功能,观察是否成功达到依赖注入:
编写测试类CDPlayerTest.java:

package soundsystem;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
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;

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

    @Test
    public void cdShouldNotBeNull(){
      cd.play();
    }

}

测试结果:正在播放 彭羚的 如梦初醒
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值