跟我重温spring---IOC(1)

IOC: 控制反转 

    将类的创建权力反转给spring框架,由spring框架来创建类对象,方便解耦。

IOC模块需要引入的jar包

Beans :Bean工厂及Bean装配

Core :IOC及DI 的基本实现

 Context :Spring上下文即IOC容器

 Expression Language :SPEL  Spring表达式语言

 

    还需要引入Spring依赖的日志包

com.springsource.org.apache.commons.logging-1.1.1.jar

com.springsource.org.apache.log4j-1.2.15.jar    -----(实现)

 

要将项目中的类的创建权反转给Spring,需要创建Spring的配置文件,配置文件可以是任意名称,但建议使用默认名称:ApplicationContent.xml便于维护。

编写配置文件需要先引入约束,Spring官方给的约束头信息在

spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html  文件中;

具体约束如下:

<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">
                </beans>

 

配置Bean管理

//Service的创建交给spring
<bean id="userService" class="com.spring.demo1.UserServiceImpl"/>

 

    获取Bean

public void demo2(){
            // 使用Spring的工厂:
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            // 通过工厂获得类:
            UserService userService = (UserService) applicationContext.getBean("userService");
            userService.sayHello();
        }

 

Spring框架中的工厂

1. ApplicationContext接口
    * 使用ApplicationContext工厂的接口,使用该接口可以获取到具体的Bean对象
    * 该接口下有两个具体的实现类
        * ClassPathXmlApplicationContext            -- 加载类路径下的Spring配置文件
        * FileSystemXmlApplicationContext           -- 加载本地磁盘下的Spring配置文件
 
2. BeanFactory工厂(是Spring框架早期的创建Bean对象的工厂接口)(了解)
    1. 使用BeanFactory接口也可以获取到Bean对象
        * 代码如下:
            public void run(){
                BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
                UserService us = (UserService) factory.getBean("us");
                us.sayHello();
            }
 
    2. BeanFactoryApplicationContext的区别
        * BeanFactory               -- BeanFactory采取延迟加载,第一次getBean时才会初始化Bean
        * ApplicationContext        -- 在加载applicationContext.xml时候就会创建具体的Bean对象的实例,还提供了一些其他的功能
            * 国际化处理
            * 事件传递
            * Bean自动装配
            * 各种不同应用层的Context实现

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值