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();
}
}
本文介绍了Spring框架中的自动装配机制,包括组件扫描与自动装配的具体应用。通过实例展示了如何使用@Component注解来标记类并由Spring自动创建bean,以及如何通过@Autowired实现依赖注入。

被折叠的 条评论
为什么被折叠?



