在Spring IOC容器中配置Bean

在Spring IOC容器中配置Bean

  • 在XML文件中通过Bean节点来配置bean
package com.metadata.action;

public class HelloWord {
private String name;
public void setName(String name) {
    this.name = name;
}
public HelloWord(){
    System.out.println("HelloWord对象创建");
}
public void say(){
    System.out.println("Tom name:"+name);
}
}
<!--
     配置Bean
    class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参构造器
    id:标示容器中的Bean,id唯一
 -->
    <bean id="helloWord" class="com.metadata.action.HelloWord">
        <property name="name" value="汤姆" />
    </bean>
  • ID :Bean的名称。
    -在IOC容器中必须唯一
    -若id没有指定,Spring自动将类名作为Bean的名字
    -id可以指定多个名字,名字之间可用逗号、分号、或空格分隔。

调用过程

public class SpringTest {
    @Test
    public void beanTest(){
        //首先创建spring的IOC容器对象
        ApplicationContext ioc=new ClassPathXmlApplicationContext("/spring-context.xml");
        //从IOC容器中获取Bean实例
        HelloWord he=(HelloWord)ioc.getBean("helloWord");
        he.say();

    }
}

ApplicationContext

  • ApplicationContext的主要实现类:
    -ClassPathXmlApplicationContext:从类路径下加载配置文件。
    -FileSystemXmlApplicationContext:从文件系统中加载配置文件。

  • ConfigurableApplicationContext扩展于ApplicationContext,新增两个主要方法:refresh()和close(),让ApplicationContext具有启动,刷新和关闭上下文的能力

  • ApplicationContext在初始化上下文时就实例化所有的单例Bean。

  • WebApplicationContext是专门为WEB应用而准备的,它允许从相对于WEB根目录的路径中完成初始化工作。

这里写图片描述

        //首先创建spring的IOC容器对象
        //ApplicationContext代表IOC容器
        //ClassPathXmlApplicationContext:是ApplicationContext接口的实现类,该类实现从类路径下来加载配置文件
        ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-context.xml");

依赖注入的方式

  • Spring支持两种依赖注入的方式
    -属性注入
    -构造器注入
    <!-- 通过构造器来配置bean属性 -->
    <bean id="dog" class="com.metadata.action.Dog">
    <constructor-arg value="哈士奇" index="0"/>
    <constructor-arg value="yellow" index="1" />
    <constructor-arg value="2" type="int"/>
    </bean>
    <!-- 使用构造器注入属性值可以指定参数的位置和和参数的类型。以区分重载构造器 -->
    <bean id="dog2" class="com.metadata.action.Dog">
    <constructor-arg value="柴犬" type="java.lang.String"/>
    <constructor-arg value="red" type="java.lang.String" />
    <constructor-arg value="10.4" type="java.lang.Double"/>
    </bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值