什么bean,在Spring里可以理解为
组件。可以联系一下我在前一篇笔记《理解Spring框架的控制反转——学习笔记》中放进IoC容器里的东西,比如说放在容器实例化的类,在容器中依赖注入的类...等等。可以先配置一个简单的bean看看,代码如下:
首先是一个创建一个Bean类,其实也就是个普通的类,为其中属性提供了setter而已:
复制代码
public class Fruit{
private String color;
private String name;
public Fruit(){}
public Fruit(String name,String color){
this.color=color;
this.name=name;
}
public void setColor(String color) {
this.color = color;
}
public void setName(String name) {
this.name = name;
}
public void mySaid(){
System.out.println("我是"+name+",我的颜色是:"+color);
}
}
复制代码
配置文件就索性名为bean.xml,放在classpath下,以便待会实例化容器的时候找到它,代码如下:
复制代码
< 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">
复制代码
这样一来,bean就配置好了。上面代码里setter注入用了两种写法,效果是相同的,都会将value值注入到相应的属性中。
而且要注意的是,标签是指要注入的属性,它是通过name的值来找到相应属性的。正如上面代码所示, ,那么它就会去找这个bean所设置的类里(上面代码里,类为”com.czh.Fruit")的一个名为setColor的方法,然后注入value值。同理,如果property的name为“abc",则容器也会到类里找setAbc方法。
组件写好了,也配置进了容器中,下一步就是实例化容器:
复制代码
public class Main{
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");//实例化容器
fruit.mySaid();
}
}
复制代码
容器实例化的方法还有很多种,用ClassPathXmlApplicationContext类可以从classpath路径上实例化容器。实例化容器之后,就可以用getBean方法去找配置在容器中的组件了,比如context.getBean("fruit");这个时候容器就把该注入的内容注入进组件,并实例化该组件,于是这时候调用该组件的mySaid()方法,可以看到输出"我是apple,我的颜色是:red".
上面介绍了最简单的配置,和实例化容器。现在来看看如何在Bean配置文件指定对Bean的引用..这句话可以理解成这样:A类中需要引用B类的方法,首先需要在A类中实例化B类,然后使用B类方法。但是在使用容器的情况下,可以通过Setter或者构造器把B类注入到A类中...这就是一个Bean对另一个Bean的引用了,具体看下面代码:
复制代码
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;
}
public void setPrice(Price price){
this.price=price;
}
public void mySaid(){
System.out.println("我是"+name+",我的颜色是:"+color+",我的价格是:"+price.getPrice());
}
}
复制代码
这里需要用到Price类:
复制代码
public class Price{
private String price;
public void setPrice(String price){
this.price=price;
}
public String getPrice(){
return price;
}
}
复制代码
于此同时,bean的配置应该改为:声明另一个bean(即price),并注入到Fruit中
复制代码
< 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">