spring 4.x的bean装配机制

Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系。当描述bean如何进行装配时,Spring具有非常大的灵活性,它提供了三种主要的装配机制:
1.在XML中进行显式配置。
2.在Java中进行显式配置。
3.隐式的bean发现机制和自动装配。

1.自动化装配bean

1.1组件扫描(component scanning):Spring会自动发现应用上下文中所创建的bean。
1.2自动装配(autowiring):Spring自动满足bean之间的依赖。

public interface CompactDisc {
    void play();
}
/**
 *这个简单的注解表明该类会作为组件类,并告知Spring要为这个类创建
bean。没有必要显式配置SgtPeppersbean,因为这个类使用了
@Component注解,所以Spring会为你把事情处理妥当。
 */
@Component
public class SgtPeppers implements CompactDisc{
    private String title = "sgt pepper";
    private String artist = "Beatles";
    @Override
    public void play() {
        System.out.println("playing "+title + " by " +artist);
    }
}
/**
 *组件扫描默认是不启用的。我们还需要显式配置一下Spring,
从而命令它去寻找带有@Component注解的类,并为其创建bean。
 */
@Configuration
@ComponentScan
public class CDPlayerConfig {
}

@ComponentScan默认会扫描与配置类相同的包。因为CDPlayerConfig类位于soundsystem包中,因此Spring将会扫描这个包以及这个包下的所有子包,查找带有@Component注解的类。这样的话,就能发现CompactDisc,并且会在Spring中自动为其创建一个bean。
使用xml配置:

<!-- 配置包的自动扫描 -->
    <context:component-scan base-package="com.test.springhello" />

测试bean,这个bean所给定的ID为sgtPeppers,也就是将类名的第一个字母变为小写。

    public void testApp() {
        ApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
//      也可以使用这种方式获得
//      SgtPeppers sgt = context.getBean(SgtPeppers.class);
        SgtPeppers sgt = (SgtPeppers) context.getBean("sgtPeppers");
        sgt.play();
    }

也可以这样,修改名字

@Component("sgt")
public class SgtPeppers implements CompactDisc{
    private String title = "sgt pepper";
    private String artist = "Beatles";
    @Override
    public void play() {
        System.out.println("playing "+title + " by " +artist);
    }
}

还可以使用basePackages 配置

@ComponentScan(basePackages = "com.test.springhello")
public class CDPlayerConfig {

}

2.通过为bean添加注解实现自动装配


@Component
public class CDPlayer implements MediaPlayer{
    private CompactDisc cd;

//  这里可以自动装配唯一符合条件的注解 表示可以没有bean匹配
// 将required属性设置为false时,Spring会尝试执行自动装配,但是如果没有匹配的bean的话,Spring将会让这个bean处于未装配的状态。
//但是,把required属性设置为false时,你需要谨慎对待。如果在你的代码中没有进行null检查的话,这个处于未装配状态的属性
有可能会出现NullPointerException。
    @Autowired(required = false)
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }
//  
    @Autowired
    public void setCd(CompactDisc cd) {
        this.cd = cd;
    }


    public CompactDisc getCd() {
        return cd;
    }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值