Spring 配置Bean

来源:互联网 发布:淘宝客开发平台 编辑:程序博客网 时间:2024/05/22 13:54

**

Spring 配置Bean

**

1.配置形式 :基于XML文件的方式;基于注解的方式

2.Bean的配置方式 :通过全类名(反射),通过工厂方法,FactoryBean。

3.依赖注入的方式:属性注入,构造器注入

例:
3.1属性注入
applicationContext.xml

<!--配置bean--> <bean id="helloWorld" class ="全类名">         <!--通过setter方法注入-->     <property name="name2" value="spring"></property> </bean> 

3.2 构造器注入

<!--通过构造方法来配置bean的属性--> <!--可以指定参数的位置和参数的类型,以区分重载的构造器--> <bean id="car" class="全类名">    <constructor-arg value="Audi" index="0"></constructor-arg>    <constructor-arg value="ShangHai" index="1"></constructor-arg>    <constructor-arg value="30000" index="2"></constructor-arg>    <constructor-arg value="240" type="int"></constructor-arg> </bean>
public class Main{  public static void main(String args[]) {   //创建spring的IOC容器对象              ApplicationContext ctx = new ClassPathXmlApplcationContext("applicationContext.xml");  //从IOC容器中获取Bean实例            HelloWorld helloWorld=(HelloWorld) ctx.getBean("helloWorld");            HelloWorld helloWorld= ctx.getBean(HelloWorld.class);//不能保证唯一            System.out.println(helloWorld);             //             Car car = (Car) ctx.getBean("car");    } }
//Bean对象public class Car{  private String Brand;  private String corp;  private double price;  private int maxSpeed;  public Car(String brand,String corp,int pprice){   super();   this.brand = brand;   this.corp = corp;   this.price = price;  }  public String toString(){    return "Car[brand="+brand+",corp="+corp+",price="+price+",maxSpeed="+maxSpeed+"]";  }}

注意: id: 标识容器中bean,id唯一
class: bean的全类名,通过反射的方式在 IOC容器中创建Bean,要求Bean中必须有无参的构造器

4.IOC容器
ApplicationContext 代表IOC容器,实际上是一个接口
BeanFactory:IOC容器的基本实现,面向spring本身的
ApplicationCOntext:提供了更多的高级特性(直接使用这个)
配置Bean之前,必须先实例化IOC容器,只有实例化后,才可以从IOC里获取Bean实例使用
ApplicationContext的主要实现类:
ClassPathXmlApplicationContext:从类路径下加载配置文件
FileSystemXmlApplicationContext:从文件系统中加载配置文件
ApplicationContext 在初始化上下文时就实例化所有单例的Bean