Spring:Ioc中Bean的配置

1.1配置元数据:

需要向Spring容器提供相关的信息,以便实例化Bean并指定如何对这些Bean进行装配,提供的信息被称为配置元数据。

Spring容器通过获取应用程序编写的类和配置元数据相结合,来创建和装配Bean。

Spring容器通过了传统格式的XML配置,基于注解的配置和基于Java的配置。以下文章将学习基于XML的配置。

1.2Bean的配置

Spring Ioc容器的目的就是管理Bean,这些Bean将根据配置文件中的Bean定义进行创建,定义主要包含以下信息

·类名:用于定义Bean的实现类

·Bean行为定义:定义了Bean在容器中的行为,包括作用域,初始化方式,生命周期等

·Bean创建方式定义:说明通过构造器还是工厂方式创建Bean

·Bean之间的关系定义:也就是依赖关系的定义

1.3Bean的命名

每个Bean可以有一个或多个id,第一个id称为"标识符",其余id被叫做"别名";id在Ioc容器中必须唯一

   1.3.1指定id,必须在Ioc容器中唯一;

<bean id="student" class="POJO.Student"></bean>//指定唯一的Id

 ClassPathXmlApplicationContext xmlApplicationContext=new ClassPathXmlApplicationContext("Configuration/spring-config.xml");
 Student student=xmlApplicationContext.getBean("student",Student.class);//通过Id获取Bean
 System.out.println(student);

1.4Bean的实例化

1.4.1使用构造器实例化Bean

        使用构造器实例化Bean,分为无参构造器和有参构造器。当使用无参构造器是,class属性指定的类必须有空构造器

<bean id="student" class="POJO.Student"></bean>//使用无参构造器构造

    public Student() {    //无参构造
    }

    public Student(String name) {  //带参构造
        this.name = name;
    }

<bean id="student" class="POJO.Student">
    <constructor-arg index="0" value="SJ"></constructor-arg>   //带参构造器构造Bean
</bean>

1.4.2使用静态工厂方式实例化Bean,使用这种方式除了指定必须的class属性,还要指定factory-method属性来指定实例化Bean的方法,而且静态工厂方法也允许指定方法参数。

    <bean id="student2" class="POJO.StudentStaticFac" factory-method="newInstance">
        <constructor-arg index="0" value="sj"></constructor-arg>
    </bean>

    public static Student newInstance(String name)
    {
        return new Student(name);
    }


1.4.3实例工厂方法实例化Bean,使用这种方式不能指定class属性,必须使用factory-bean属性来指定工厂bean,factory-method属性指定实例化Bean的方法,而且使用实例工厂方法允许指定方法参数。

    <bean id="studentFac" class="POJO.StudentFac"></bean>
    <bean id="student3" factory-bean="studentFac" factory-method="newInstance">
        <constructor-arg index="0" value="Sj"></constructor-arg>
    </bean>

    public Student newInstance(String name)
    {
        return  new Student(name);
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值