关于Spring中自动化装配bean的简单技巧
Spring中有三种配置方案,分别是在xml中进行显示配置,在java中进行显示装配,隐式的bean发现机制和自动装配,但是建议尽可能的使用自动装配bean,显示配置越少越好。
首先xml文件中的自动化配置
一、约束条件的配置
1、打开Windows下面的Preference
2、搜索cata打开xml下面的xml catalog
3、点击add 打开filesystem 找到已下载的spring-context-4.2.xsd文件key type选择Schema location,把Location最后面的spring-context-4.2.xsd复制到key后面,点击ok就行了
4、将xml文件open with xml Editor
5、在新的xml文件下面点击Design
6、右键点击bean打开Edit Namespace
7、add添加再点击 Specify New Namespace 打开Browse找到之前配置的http://www.springframework.org/schema/context/spring-context-4.2.xsd(我的是Spring4.2),并按照下面的格式填写,之后点击ok就行了
二、代码书写
1、在xml文件中写添加 <context:component-scan base-package="packageName"></context:component-scan>
2、普通装配赋值
@Component("car")
// 等效于<bean name="car" class="Trainsport.Car">
public class Car {
//赋值方法两种
//放在数据类型上面 放在set方法上面(推荐使用)
@Value("劳斯莱斯")
private String type;
//@Value("劳斯莱斯")
public void setType(String type) {
this.type = type;
}
}
对象进行装配赋值
@Component("peo1")
public class People {
@Autowired //根据类型自动检测装配 匹配多个对象无法选择注入那一个对象
@Qualifier("car") //根据名字name选择注入对象(为auowired做辅助用)
//指名道姓的注入对象@Resource(name="car")
private Car car;
}
关于初始化init与销毁的自动装配
@PostConstruct //等效于init-method
private void init() {
}
@PreDestroy //等效于destory-method
private void destory() {
}