Spring中bean配置的学习笔记(三)

2014-11-24 02:08:36 · 作者: · 浏览: 3
...
复制代码
至此,就配置完成了,如果任何具有@Requried注解的属性为设置,就会抛出BeanInitializationException
之前所提出的第二个问题是:每一个Bean都要自己配置和注入,有没有什么办法可以减少手工配置?
这时候就要用到”自动装配",与@Requried注解一样,自动装配也可以通过注解来完成,即@Autowired。同样,在Spring 2.5版本之前,自动装配是由中autowire属性来完成的,大概像这样,就可以将 “与要注入的属性名相同的bean” 自动装配(也可以直接理解为自动setter),相应的还有autowire="byType",autowire="constructor"...我就不贴出代码详细说明了,直接来看看基于注解的自动装配。
先来看看@Autowired如何设置:
复制代码
public class Fruit{
private String color;
private String name;
private Price price; //Price类
public Fruit(){}
public Fruit(String name,String color,Price price){
this.color=color;
this.name=name;
this.price=price;
}
public void setColor(String color) {
this.color = color;
}
public void setName(String name) {
this.name = name;
}
@Autowired
public void setPrice(Price price){
this.price=price;
}
 public void mySaid(){
  System.out.println("我是"+name+",我的颜色是:"+color+",我的价格是:"+price.getPrice());
}
}
复制代码
如上面代码所示,在setter或者构造器前加上@Autowired即可,Spring会去容器中查找与其setter类型兼容的组件,然后注入。
xml配置代码与@Required相同,加一个就可以了。
需要注意的一点是,@Autowired会自动检查是否被注入,效果与@Requried类似,如果发现未注入就会抛出异常
为了图方便,我们还可以这样做:(直接在字段上加@Autowired注解,这样就不用自己写setter方法了)
复制代码
public class Fruit{
private String color;
private String name;
@Autowired
private Price price; //Price类
public Fruit(){}
public Fruit(String name,String color,Price price){
this.color=color;
this.name=name;
this.price=price;
}
public void setColor(String color) {
this.color = color;
}
public void setName(String name) {
this.name = name;
}
 public void mySaid(){
  System.out.println("我是"+name+",我的颜色是:"+color+",我的价格是:"+price.getPrice());
}
}
复制代码
如果你想使用@Autowired注解,又想注入特定的组件,可以使用@Qualifier注解指定特定组件的名字。或者直接使用@Resource注解指定要注入组件的名字。具体的还是来看看代码:
复制代码
public class Fruit{
private String color;
private String name;
@Autowired
@Qualifier("price");
private Price price; //Price类
...
}
复制代码
基于注解的自动装配已经为我们减少了部分要亲手配置的代码...但是觉得这个还不够,还可以看看spring 2.5提供的又一个强大特性:自动扫描组件
它能够从classpath里自动扫描、侦测和实例化组件,它所侦测的是具有特定注解的组件,该注解为@Component。
看看代码吧:
复制代码
@Component
public class Fruit{
private String color;
private String name;
@Autowired
@Qualifier("price");
private Price price; //Price类
...
}
复制代码
而在xml中的配置,也很简单,就像@Autowired那样只需要一句话:
base-package指明了要扫描的类,各类之间可以用逗号分隔。
此时的xml中已经不需要手动配置各个组件的bean了,它们默认的id为首字母小写的类名(比如:fruit),代码如下:
复制代码
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
复制代码