复制代码
从上面的配置中,应该可以很清楚看到,要引用bean只需要在property下用标签去获得bean的id即可。
当然,也可以这么写:
还有另一个引用bean的方式,那就是:内部bean。内部bean的意思就是说直接把... 写在Fruit Bean的property下。这样说可能不是很明白,那就看看下面的代码吧:(内部bean的缺点是,放在的Fruit Bean里面,则只有Fruit Bean可以引用它,其他的Bean是无法找到它的)
复制代码
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
...
...
复制代码
最基本的注入配置已经了解了。接下来应该考虑的两个问题是:1、假如配置的时候忘记了注入怎么办,漏掉了几个property导致输出都是null却很难从那么多配置中一下找到写少的部分。2、每一个Bean都要自己配置和注入,有没有什么办法可以减少手工配置?
这两个问题的解决就要看“基于注解的配置:@Required和@Autowired"...
首先来看看@Requried,顺便理解一下注解在框架中起的作用
检查属性是否注入是上面所说要考虑的两个问题之一。在spring中可以使用依赖检查的特性来解决这个问题,依赖检查很简单,只需要在bean里添加一个dependency-check属性就可以了,具体的看看下面代码:
复制代码
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
...
...
复制代码
dependency-check="all"意味着对简单类型的注入,和对象的注入(即bean的引用)都进行检查。
dependency-check="simple"意味着对简单类型(int,string...)的注入进行检查。
dependency-check="object"意味着对 对象的注入(即bean的引用)进行检查。它们一旦检查未setter,就会抛出UnsatisfiedDenpendencyException。
不过这个dependency-check好像在spring 3.0中使用会报错,所以当基于注解的@Requried可以用于与它一样的作用的时候,就使用@Requried注解吧。
Spring的一个Bean后置处理器(RequiredAnnotationBeanPostProcessor)可以检查所有具有@Requried注解的属性是否被设置,可以继续上面水果类的例子看看这个@Requried如何放置,代码如下:
复制代码
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;
}
@Requried
public void setColor(String color) {
this.color = color;
}
@Requried
public void setName(String name) {
this.name = name;
}
@Requried
public void setPrice(Price price){
this.price=price;
}
public void mySaid(){
System.out.println("我是"+name+",我的颜色是:"+color+",我的价格是:"+price.getPrice());
}
}
复制代码
放置@Required注解很简单,像上面代码那样就可以了。Bean.xml那里还得做点功夫,不过也很简单,Spring 2.5以上的版本,我们只需要在xml中加上一句话就可以了,像这样: ,不过还是看看代码吧,在beans那块加了些东西,否则会无法使用标签。代码如下:
复制代码
< 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">