自动装配bean【Spring 入门】

本文介绍了Spring框架中bean的自动装配机制及其配置方式,包括@Component、@Autowired和@ComponentScan注解的使用方法,并通过实例展示了这些注解的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring中bean的装配有三种配置方式,我们应该尽可能的使用自动装配的机制,显示配置越少越好。

自动装配要用到的注解:

@Component   表明该类为组件类,并告知Spring要为这个类创建bean。

@Autowired  根据类型,为成员变量、构造方法或其他方法自动装配bean。

@ComponentScan  在Spring中启用自动扫描

下面通过代码来说明这几个注解的用法:

组件类:

package com.yykj.soundsystem;

import org.springframework.stereotype.Component;

@Component("sgt")//括号内为组件名,可以不写,默认为类名小写首字母
public class Mayday implements CompactDisc {

    public void play(){
        System.out.print("Play");
    }
}
Java配置类:
package com.yykj.soundsystem.config;

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

@Configuration
@ComponentScan(basePackages = "com.yykj.soundsystem")//自动扫描的基础包
public class CDPlayerConfig {
}
单元测试类:
package com.yykj.soundsystem;

import com.yykj.soundsystem.config.CDPlayerConfig;
import org.junit.*;
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(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {

    @Rule
    public final StandardOutputStreamLog log = new StandardOutputStreamLog();
    @Autowired
    private CompactDisc cd;

    @Autowired
    private MediaPlayer player;
    @Test
    public void cdShouldNotBeNull(){
        Assert.assertNotNull(cd);
    }

    @Test
    public void TestPlay(){
        player.play();
        Assert.assertEquals(log.getLog(), "Play");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值