最近又把spring实战拿出来翻了一遍,看到了第二章Bean装配,记录下来以此来加深自己的印象。
第二章,我的自我总结是Bean的装配会有三种,(1)自动化装配,(2)基于java的显式装配,(3)基于XML的显式装配,从一开始我什么都不会,大家懂的,大学都是玩过来的,只是我玩的比别人厉害点罢了,一直用的是基于XML的显式装配,对于bens本书的作者来说,大力提倡第一种,因为可以省去很多麻烦,最不推崇的就是基于XML的显式装配,但是我实习了这么久,也没觉得有什么麻烦的,估计的习惯了吧,但是,毕竟本书作者推崇的肯定是对的吧 ,以后尽量多使用使用,就熟悉了。言归正传。
2.1 首先我先记录第一种作者最推崇的自动化装配Bean
Spring自动化装配Bean,在我个人看来分为以下步骤:(1)咱们先是要创建咱们需要的Bean,然后需要启动组件扫描,然后Spring就会自动发现应用上下文中所创建的bean。(2)利用注解的方式,Bean会自动装配到另一个Bean中,也就是注入吧,Spring会自动满足bean之间的依赖关系。
我们根据下面的代码来更加直观的了解里面的机制
2.1.1 创建可被发现的bean
package soundsystem;
public interface CompactDisc{ //唱片接口
void play(); // play方法
}
带有@Component注解的CompactDisc实现类SgtPeppers
package soundsystem;
import org.springframework.stereotype.Component;
@Component //这个注解表明该实现类是一个组件类,它会告诉Spring要为这个组件类创建bean,但是组件扫描默认是不开启的,所以需要显式配置一下Spring,命令Spring去寻找带有这个注解的类,找到了之后,为这个类创建bean
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注解启用了组件扫描(通过Java代码定义Spring装配规则)(推荐)
package soundsystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan //利用此注解启用了组件扫描,且默认扫描与该配置类相同的包及下面的所有子包
public class CDPlayerConfig { //没有显式的声明任何bean
}
或者也可以通过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="soundsystem" /> // <context:component-scan>对应于Java代码中的@ComponentScan
</beans>
@Component注解(推荐)或者@Name还可以为组件扫描的bean命名,也就是为bean设置不同的ID(默认ID为类名(第一个字母小写))
@Component(“lonelyHeartsClub”)
public class SgtPeppers implements CompactDisc {
}
@Name(“lonelyHeartsClub”)
public class SgtPeppers implements CompactDisc {
}
@ComponentScan默认扫描与peiz配置类相同的包及下面的子包,但是我们也可以自己定义像扫描的包
@ComponentScan(basePackages="soundsystem”)
public class CDPlayerConfig { //没有显式的声明任何bean
}
也可以扫描多个包
@ComponentScan(basePackages={"soundsystem”,“video”})
public class CDPlayerConfig { //没有显式的声明任何bean
}
不推荐所设置的包以String类型表示
@ComponentScan(basePackageClasses={CDPlayer.class,DVDPlayer.class})//这些类所在的包作为组件扫描的基础包
public class CDPlayerConfig { //没有显式的声明任何bean
}