Spring 学习笔记【一】自动装配bean

注:本系列博客是我学习《Spring in Action 4》的学习笔记,部分问题可能有雷同。如有侵权请私信指出,立马删除。

创建可以被发现的Bean

下面的代码创建了一个接口与一个接口实现,并为实现添加了一个@Component注解,告知Spring要为这个类创建Bean。

public interface CompactDisc {
  void play();
}
@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);
    }
}
启用组件扫描

@ComponentScan注解能够在Spring 中启用组件扫描,该注解默认扫描配置类相同包以及其子包,查找带有@Component注解的类,并且在Spring 中为其创建Bean.

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

如果我们的不想通过java注解的方式启用组件扫描,或者组件并不在@ComponentScan同包或者子包下面的话。可以使用xml文件来启用组件扫描。

<?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"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="pub.zhouhui" />
</beans>

####测试

package pub.zhouhui;

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 static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {

    @Autowired
    private CompactDisc cd;

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

@RunWith(SpringJUnit4ClassRunner.class)便于在测试开始的时候自动创建Spring的应用上下文。

@ContextConfiguration会告诉他需要在CDPlayerConfig中加载配置。

@Autowired将CompactDisc bean 注入到测试代码中

转载于:https://my.oschina.net/zhouhui321/blog/790967

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值