《Spring in action》之装配Bean
创建应用对象之间协作关系的行为通常称为装配,这也是依赖注入的本质。
Spring装配Bean的三种主要机制:
1.在XML中进行显示配置
2.在java中进行显示配置
3.隐式的bean发现机制和自动装配
1.自动化装配
1.组件扫描:spring会自动发现上下文中创建的Bean
2.自动装配:Spring自动满足bean之间的依赖
组件扫描
public interface Phone { void speak(); }
@Component定义组件,@Component("apple")可以指定组件id
@Component public class Apple implements Phone{ @Override public void speak() { System.out.println("apple speak"); } }
创建配置类:
注解@ComponentScan启用了组件扫描,basePackages扫描指定单个包,多个包(basePackages ={"",""})
@Configuration //@ComponentScan(basePackages = "com.spring.ioc.autowiring") @ComponentScan(basePackages = {"com.spring.ioc.autowiring","com.spring.di"}) public class PhoneConfig { }
这里也可以不用这个类配置@ComponentScan,可用xml配置
<!-- 启用组件扫描--> <context:component-scan base-package="com.spring.ioc.autowiring"/>
测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = PhoneConfig.class) public class PhoneTest { @Autowired private Phone phone; @Test public void checkPhone(){ phone.speak(); Assert.assertNotNull(phone); } }
自动装配
@Autowired
public class Xiaoming { private Phone phone; //这里不管是构造方法、set方法、普通方法@Autowired都能自动装配 @Autowired public Xiaoming(Phone phone) { this.phone = phone; } public void speak(){ phone.speak(); } }
2.通过java代码装配bean
代码如下:
public class XiaoMi implements Phone{ @Override public void speak() { System.out.println("小米。。。。。。"); } }
创建配置类:
@Configuration public class JavaConfig { @Bean public Phone getPhone(){ return new XiaoMi(); } }
junit测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = JavaConfig.class) public class JavaConfigTest { @Autowired private Phone phone; @Test public void checkPhone(){ phone.speak(); Assert.assertNotNull(phone); } }
也可以通过如下main测试
public static void main(String[] args) { //加载java配置类获取Spring应用上下文 ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class); XiaoMi xiaoMi= ac.getBean(XiaoMi.class); xiaoMi.speak(); }
3.在XML中进行显示配置
声明bean用<bean id="xxx" class="xxx">标签