Spring IoC 实现方式

在Spring 基本概念里我们已经了解了IoC的思想,本篇讨论Spring IoC的两种实现方式和相关配置。

一、通过XML文件配置实现

1、 首先要通过XML文件配置实现我们要引入最基本的Spring相关jar包并生成环境

  • spring-beans-4.3.9.RELEASE.jar
  • spring-context-4.3.9.RELEASE.jar
  • spring-core-4.3.9.RELEASE.jar
  • spring-expression-4.3.9.RELEASE.jar
  • commons-logging-1.1.1.jar
  • log4j-1.2.14.jar
    这里写图片描述

2、创建Spring配置文件,并引入schema约束

这里写图片描述

3、创建测试类,利用Spring配置来创建对象并测试

  • 客户类,要利用Spring实例化的类
package com.sitech.test1;

public class Custom {

    public void print() {
        System.out.println("Custom.print()");
    }
}

  • 在applicationContext位置文件里配置Custom
<?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 id="custom" class="com.sitech.test1.Custom"></bean>
</beans>
  • 测试类
package com.sitech.test1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test1 {
   

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Custom custom = (Custom) applicationContext.getBean("custom");
        custom.print();
    }
}
  • 输出结果
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Custom.print()

4、bean实例化的三种方式

  • 使用类的构造方法创建对象
<bean id="custom" class="com.sitech.test1.Custom"></bean>
  • 使用静态工厂创建对象
package com.sitech.test2;

public class CustomStaticFactory {

    public static Custom getCustom() {
        return new Custom();
    }
}
<bean id="custom" class="com.sitech.test2.CustomStaticFactory" factory-method="getCustom"></bean>
  • 使用实例工厂创建对象
package com.sitech.test3;

public class CustomFactory {

    public Custom getCustom() {
        return new Custom();
    }
}
<bean id="customFactory" class="com.sitech.test3.CustomFactory"></bean>
<bean id="custom" factory-bean="customFactory" factory-method="getCustom"></bean>

5、bean标签属性介绍

  • id:标识,实例名,建议使用
  • name:标识,不建议使用
  • class:所要创建的对象的类名全路径
  • scope
    • singleton:单例,默认值
    • prototype:原型(多例࿰
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值