Spring笔记:基于XML的DI-IoC容器中bean的简单装配

此仅为个人笔记,若有不周之处,万望指正,不胜感激。

在Spring框架中对象是不需要自己创建的,由容器提供,需要的时候像容器索取即可,这样的好处在于降低代码间耦合,提高代码复用性,且有助于后期维护。Spring框架中主要使用BeanFactory和ApplicationContext两种容器,下面例子使用的是ApplicationContext容器。

ApplicationContext容器的简单使用分以下几步:

  1. 配置xml文件,配置文件名Spring官方建议使用applicationContext.xml,代码如下:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        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.xsd">
    
    	    <!-- 注册Bean  -->
    	<bean id="MyService" class="top.bwextend.service.SomeServiceImp1"/>
    </beans>
    <bean id="MyService" class="top.bwextend.service.SomeServiceImp1"/>作用等价于:"SomeServiceImp1 MyService=new SomeServiceImp1();"注册Bean等同于使用无参构造函数声明了一个对象,所以必须保证此Bean有无参构造函数。至于参数的初始化,先不做讨论。
  2. 使用ApplicationContext声明一个容器引用,而ApplicationContext本身是一个接口,所以便用它的实现类ClassPathXmlApplicationContext或FileSystemXmlApplicationContext声明对象。通过ClassPathXmlApplicationContext类来声明容器ApplicationContext对象是在类路径下寻找xml文件,而通过FileSystemXmlApplicationContext类来创建容器ApplicationContext对象是在项目根目录下寻找xml文件,还可以在系统目录下寻找。代码如下:
    package top.bwextend.test;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import top.bwextend.service.ISomeService;
    import top.bwextend.service.SomeServiceImp1;
    
    public class MyTest {
    	
    	public void test01() {
    		ISomeService service=new SomeServiceImp1();
    		service.doSome();
    	}
    	@Test
    	public void test02() {
    		//创建容器对象,加载Spring配置文件
    		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    		ISomeService service=(ISomeService) ac.getBean("MyService");
    		service.doSome();
    	}
    }
    ClassPathXmlApplicationContext("applicationContext.xml")代码中applicationContext.xml为第一步中配置的xml文件。声明完容器对象之后便可通过容器对象的getBean()方法得到Bean,getBean()方法的参数为xml文件中声明的对应Bean的id属性。
  3. 上述代码中doSome()函数为该Bean的一个方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值