在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:原型(多例