自动化装配bean
组件扫描(component scanning):Spring会自动发现应用上下文中所创建的bean
自动装配(autowiring): Spring自动满足bean之间的依赖
@Component
注解表明类会成为组件类,并告知Spring要为这个类创建bean,不指定beanId,会把类名的第一个字母变成小写作为bean id
@Component("helloWorld")
public class HelloWorld {
// TODO
}
@Named
可以在大多数场景下和@Component互相替换
@ComponentScan
组件扫描默认不启用,需要显示配置一下Spring。
不指定基础包的话,默认会扫描与配置类系统的包, xml中使用context:component-sacn启用
@Configuration
@ComponentScan
public class HelloWorldConfig() {
// TODO
}
@ComponentScan("com.mypackage")
@ComponentScan(basePackages="com.mypackage")
@ComponentScan(basePackages={"com.mypackage1", "com.mypackage2"}
@Autowired
不仅能够用在构造器上,还可以用在Setter方法上(setter方法的参数可以被自动装配)
@Inject 大多数场景下可以和@Autowired互相替换
测试的时候可以使用
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=…)指定从哪里加载配置
通过java代码装配bean
自动化装配无法完成,比如三方库中的bean, 类型安全
@Configuration注解表明这个类是一个配置类,应该包含在Spring应用上下文中如何创建bean的细节
@Bean注解在方法上,告诉Spring这个方法会返回一个对象,该对象要注册为Spring应用上下文中的bean。默认bean的id和注解的方法名是一样的
通过XML装配bean
<bean id="xxx" class="xxx">
<constructor-arg ref="xxxx" />
<cxonstructor-arg value="xxxx" />
<constructor-arg>
<list>
<value>1</value>
<value>2</value>
</list>
</constructor-arg>
<property name="xxx" ref="xxx" />
<property name="xxx" value="xxx" />
</bean>
当配置类变得很复杂时,可以拆成多个配置类,然后在一个顶层的配置类里通过@Import({aa.class, bb.class})引入其他配置。还可以通过@ImportResource引入xml文件
xml配置分拆