Spring装配Bean(一)

三种bean的装配机制

* xml中配置

* java中进行显式配置

* 隐式的bean发现机制和自动装配

自动化装配bean

Spring从两个角度来实现自动化装配:

* 组件扫描(component scanning) : Spring 会自动发现应用上下文中创建的bean

* 自动装配(autowiring): Spring自动满足bean之间的依赖

1. 创建可以被发现的bean

举个例子:创建一个类,Spring会发现它并加其创建为一个bean,然后创建另一个bean,并注入到前面bean中 。

package com.erong.interface_;

public interface CompactDisc {
	void play();
}
package com.erong.service;

import org.springframework.stereotype.Component;

import com.erong.interface_.CompactDisc;
@Component
public class SgtPeppers implements CompactDisc {
	private String title = "Sgt.Pepper's Hearts Club Band ";
	private String artist = "The Beatles";
	@Override
	public void play() {
		System.out.println("Playin "+title+" by "+artist);
	}

}

@Component注解,表示该类作为组件类,并告知Spring要为这个类创建bean

package com.erong.service;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {

}

@ComponentScan注解,能够在Spring中启用组件扫描,没有其他配置的话,默认扫描和配置类相同的包,找到@Component的类,并创建一个bean。

如果使用xml来启用组件扫描的话,使用Spring context命名空间的<context:component-scan basepackage="com.long">元素,basepackage设置扫描的路径

package com.erong.service;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.erong.interface_.CompactDisc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
	@Autowired
	private CompactDisc cpd;
	@Test
	public void test(){
		Assert.assertNotNull(cpd);
	}
}

CDPlayerTest 使用了Spring的SpringJUnit4ClassRunner,以便在测试开始的时候自动创建Spring应用的上下文

注解@ContextConfiguration会告诉需要在CDPlayerConfig中加载配置,从而找到@Component的bean,并创建。

2. 为组件扫描的bean命名

Spring上下文中所有的bean都会给定义一个id,如果给扫描的bean也定义一个唯一id

@Component(value="sgtp") 或者使用Java依赖注入规范@Named注解来为bean设置id

Note:Spring支持@Named作为@Component替换,只有细微查询,大多数情况可以互换

3. 设置组件扫描的基础包

@ComponentScan的value属性中指定包的名称

@ComponentScan(value="com.test")

如果需要配置多个基础包,basePackages配置

@ComponentScan(basePackages={"com.erong","com.test"})

除了将包设置为简单的String类型之外,@ComponentScan指定为包中包含的类或者接口

@ComponentScan(basePackageClasses={com.erong.service.SgtPeppers.class})

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

自动装配:在Spring上下文中寻找匹配某个bean需求的其他bean。

* Autowire注解

1> 构造器上添加了@Autowired注解,表示创建对象的时候,自动传入一个bean

@Autowired
public CDPlayer(CompactDisc cd){
	this.cd = cd;
}

2> 用在属性的setter方法上

@Autowired
public void setCd(CompactDisc cd) {
	this.cd = cd;
}

实际上,如果存在一个insertDisc方法,也可以使用@Autowire将bean注入

Note:

1> 不管是构造器、setter方法还是其他的方法,对于Autowire Spring都会尝试满足方法参数上声明的依赖.

2> 对于Autowire注解,假如只有一个bean,就会注入一个,存在多个就会抛异常

3> Spring上下文中不存在匹配的bean,那么在创建Spring上下文的时候,Spring将抛出异常,为了避免异常的出现,将@Autowire的 required属性设置为false

4> @Inject注解替换@Autowire,大多数场景可以互换。

猜你喜欢

转载自blog.csdn.net/ditto_zhou/article/details/80366268
今日推荐