回到首页☞
Core模块主要的功能是实现了反向控制IOC(Inversion of Control)与依赖注入DI(Dependency Injection)、Bean配置以及加载。Core模块中有Beans、BeanFactory、BeanDefinitions、ApplicationContext等几个重要概念。
Beans为Spring里的各种对象,一般要配置在Spring配置文件中:BeanFactory为创建Beans的Factory,Spring通过BeanFactory加载各种Beans;BeanDefinition为Bean在配置文件中的定义,一般要定义id与class:ApplicationContext代表配置文件。
这些类都位于org.springframework.beans和org.springframework.context中。这是Spring最核心的包。Core模块依赖于Spring的Core类库。

任何框架的核心是依赖关系,和资源有哪些是核心。
码农都有一个问题,在实际项目中玩的很溜,因为框架都是搭建好的,一般一个系统出了前几天搭建后续大家都是在自己的业务模块开发。所以,0-1才是真正的核心。
1、整体了解
1.1、Core Container 核心容器
容器是Spring的核心部分,Core Container 模块是Spring框架的基础,所有模块都构建于核心模块之上。
- Beans : Beans模块是所有应用都要用到的,它包含访问配置文件、创建和管理bean以及进行Inversion of Control / Depen-dency Injection(IoC/DI)操作相关的所有类。
- Core : Core模块主要包含Spring框架基本的核心工具类,Spring的其他组件要都要使用到这个包里的类,Core模块是其他组件的基本核心。当然你也可以在自己的应用系统中使用这些工具类。
- Context : Spring的上下文即IoC容器,通过上下文可以获得容器中的Bean。 ApplicationContext接口是Context模块的关键。 Context模块构建于Core和Beans模块基础之上,提供了一种类似于JNDI注册器的框架式的对象访问方法。
- SpEl : Expression Language模块提供了一个强大的表达式语言用于在运行时查询和操纵对象。
1.2、 Core Container 依赖关系
因为spring-core依赖了commons-logging,而其他模块都依赖了spring-core,所以整个spring框架都依赖了commons-logging。
如依赖关系Spring离不开日志,但是日志框架有多种也不一定使用commons-logging如果有自己的日志实现如log4j,可以排除对commons-logging的依赖,没有日志实现而排除了commons-logging依赖,编译报错。
1.3、构建最基础的Spring项目
1.3.1、核心容器四个包
spring-beans-4.1.3.RELEASE.jar
spring-context-4.1.3.RELEASE.jar
spring-core-4.1.3.RELEASE.jar
spring-expression-4.1.3.RELEASE.jar
1.3.2、核心容器依赖的日志包
commons-logging-1.2.jar
log4j-1.2.17.jar
commons-logging相当于一个日志接口,log4j相当于该接口的实现,如果不添加log4j包也可以,因为commons-logging也有一个简单的实现会自动使用。
1.3.3、测试类包
spring-test-4.1.3.RELEASE.jar
junit-4.10.jar(高于4.10版本还需要hamcrest-core.jar + hamcrest-library.jar)
1.3.4、测试类用到了AOP必须导入aop包
spring-aop-4.1.3.RELEASE.jar
1.3.5、pom
目前都是玩的Mavn,搜索对应包就可以找到坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>myspring</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-version>5.0.2.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring核心模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
<scope>test</scope>
</dependency>
<!-- 添加Log4J依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
</project>
2、BeanFactory工厂
2.1、核心类图
其实学习这个最好去读下源码,因为这个框架类之间层级结构比较深。
2.2、实例化BeanFactory
BeanFactory是实例化、配置、管理众多Bean的容器。这些Bean类一般是离散的,但在Spring中被配置为相互依赖。BeanFactory根据配置实例化Bean对象,并设置相互的依赖性。
BeanFactory可用接口org.springframework.beans.factory.BeanFactory表示。BeanFactory有多种实现,最常用的为org.springframework.beans.factory.xml.XmlBeanFactory。XmlBeanFactory能加载XML格式的配置文件。
实例化BeanFactory
在Web程序中用户不需要实例化BeanFactory,Web程序加载的时候会自动实例化BeanFactory,并加载所有的Beans,将各种Bean设置到各个Servlet中、Struts的Action中、或者Hibernate资源中。开发者直接编写Servlet、Action、Hibernate相关的代码即可,无须操作 BeanFactory。
在Java桌面程序中,需要从BeanFactory中获取Bean,因此需要实例化BeanFactory,构造函数的参数为配置文件的路径。例如加载ClassPath下的配置文件可以用ClassPathResource加载,然后传递给XmlBeanFactory构造函数。代码如下:
@Test
public void factoryTest(){
ClassPathResource resource = new ClassPathResource("applicationContext.xml");
XmlBeanFactory factory = new XmlBeanFactory(resource); // 获取对象工厂
AdivceImpl adivce = (AdivceImpl) factory.getBean("proxyfactory");
adivce.doAny();
}
其实这个古老的方法,已经过期了,现在已经划线不建议使用了。
使用ClassPathXmlApplicationContext 替代
@Test
public void factoryTest(){
BeanFactory container =
new ClassPathXmlApplicationContext("applicationContext.xml");
AdivceImpl adivce = (AdivceImpl) container.getBean("proxyfactory");
adivce.doAny();
}
参数applicationContext.xml为ClassPath根目录下的文件。applicationContext.xml为Spring默认的配置文件名称,默认存储在ClassPath根目录下。或者使用文件流加载任意位置的配置文件,并传递给XmlBeanFactory构造函数,例如:
@Test
public void factoryTest() throws FileNotFoundException {
String filePath ="D:\\workspace\\idea\\myspring\\src\\main\\resources\\ApplicationContext.xml";
Resource res = new FileSystemResource(filePath);
XmlBeanFactory container =new XmlBeanFactory(res);
AdivceImpl adivce = (AdivceImpl) container.getBean("proxyfactory");
adivce.doAny();
}
或者用ClassPathXmlApplicationContext加载多个配置文件(多个配置文件以字符串数组形式传入),并传递给XmlBeanFactory构造函数:
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml", "applicationContext-part2.xml"}); // 多个配置
BeanFactory factory = (BeanFactory)appContext; // ApplicationContext继承自BeanFactory接口
2.3、XmlBeanFactory配置格式
一个BeanFactory中配置了多个Bean。在XmlBeanFactory中,配置文件的根节点为< beans >,里面定义了几个< bean>子节点,每个< bean>定义一个Bean。格式如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <!-- Beans根节点 -->
<bean id="..." class="..."> <!--Bean节点,定义Bean-->
...
</bean>
<bean id="..." class="..."> <!--Bean节点,定义Bean-->
<property name="..." value="..."></property> <!-- Property定义属性 -->
<property name="..." ref="..."></property> <!-- Property定义属性 -->
</bean>
</beans>
3、配置Java Bean
一个BeanDefinition定义一个Bean,在XML中对应一个< bean >标记。Spring通过< bean >配置来实例化Bean,设置Bean的属性,以及设置Bean之间相互的依赖性。
3.1、基本配置 < bean>
一个< bean >通常需要定义id与class属性。class属性是必须的,如果有其它Bean引用了该Bean,则id属性是必须的。Bean之间通过id属性相互访问,如:
<!--要增强的对象-->
<bean id="service" class="com.wht.service.impl.AdivceImpl"></bean>
上面代码等价于
3.2、工厂模式factory-method
如果一个Bean不能通过new直接实例化,而是通过工厂类的某个方法建的,可以把class设为工厂类,用factory-method指向创建对象的法:
<!-- createInstance()是静态方法 -->
<bean id="exampleBean"
class="example.MyFactoryBean"
factory-method="createInstance" />
<!-- createInstance()是非静态方法 -->
<bean id="exampleBean2"
factory-bean="myFactoryBean"
factory-method="createInstance" />
3.3、构造函数< constructor-arg>
如果Bean的构造函数带参数,那就需指定参数,用< constructor-arg>指定
<bean id="adivce" class="com.wht.service.impl.AdivceImpl">
<constructor-arg><value>Jack</value></constructor-arg>
<!-- 构造函数参数 -->
<constructor-arg><ref bean="anotherExampleBean" /></constructor-arg>
</bean>
每个的参数的顺序要与构造函数相同。
3.4、单态模式singleton
Spring默认是单态模式,如果想使用非单例模式(称为Prototype模式), scope=“prototype”:
<bean id="adivce" class="com.wht.service.impl.AdivceImpl" scope="prototype">
<constructor-arg><value>Jack</value></constructor-arg>
</bean>
非单例下,每次请求该Bean,都会生成一个新的对象。
3.5、配置属性< property>
Spring通过Bean的setter方法设置属性。因此,需要由Spring注射的属性一般都具有公共的setter,getter方法。例如下面的配置代码:
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/dev?characterEncoding=UTF-8" />
<property name="username" value="dev" />
<property name="password" value="hcgk*2020" />
</bean>
destroy-method属性配置关闭方法。在销毁对象时会调用该方法。
注意:
<!-- 将password设为空字符串 -->
<property name="password"><value></value></property>
<!-- 将password设为null,也可以不设置 -->
<property name="password"><null /></property>
3.6、设置对象属性< ref>
使用ref标签配置Bean的id属性使用。如:
<bean id="dao" class="com.wht.dao.impl.DaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean class="com.wht.service.impl.ThreadServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
ref的内容为引用的Bean的id属性。
也可使用内部配置(或者内联配置),类似于JAVA中的匿名类对象。因为内部配置一般不会被其他的Bean引用,因此不需要配置内部Bean的id。例如:
<property name="dao">
<bean class="example.DaoImpl"></bean>
</property>
除了使用< ref>的bean属性,还可以使用local、parent,它们与bean属性的作用是一样的。不同的是,local只能使用本配置文件中的bean,而parent只能使用父配置文件中的bean,但bean则没有任何限制。
3.7、配置List属性< list>
< list>配置java.util.List类型的属性。list属性中可配置任意类型对象,如果为java对象,使用ref指定,或者< bean>定义新实例,如果是普通类型如String,int,double等,直接用字符串即可。< list>中的元素会按配置的先后顺序排序,例如:
<property name="someList">
<list>
<value>String,Integer,Double,Boolean等类型对象</value>
<ref bean="myDataSource" />
</list>
</property>
3.8、配置Set属性< set>
< set>配置java.util.Set类型的属性。Set属性中可配置任意类型对象。如果为java对象,则使用< ref>指定,或者使用< bean>重新定义新实例。如果是普通类型如String,int,double等,直接用字符串即可。例如:
<property name="someSet">
<set>
<value>String,Integer,Double,Boolean等类型对象</value>
<ref bean="myDataSource" />
<set>
</property>
3.9、配置Map属性< map>
< map>配置java.util.Map类型的属性。< entry>配置Map里的元素,key指定索引,value指定值。如果为java对象,则使用ref指定,或者使用< bean>重新定义新实例,如果key为对象,,使用key-ref属性,例如:
<property name="someMap">
<map>
<entry key="yup an entry">
<value>just some string</value>
</entry>
<entry key-ref="myDataSource">
<ref bean="serviceImpl" />
</entry>
</map>
</property>
3.10、配置Properties属性< props>
这是真正项目常用的,但是对于大企业可能会提供统一的资源配置中心,通过SDK加密传输配置信息。
使用< props>与< prop>配置Properties属性。< props/>配置一个Properties对象,< prop/>配置一条属性,属性key配置索引,例如:
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
3.11、< idref>与< ref>的区别
< idref>与< ref>的作用是一样的,都是配置java对象的。< idref>的用法也与< ref>基本相同。不同的是,< idref>只有bean与local属性,没有parent属性,如
Spring加载XML配置文件时,会检查< idref>配置的Bean存在不存在。而< ref>只会在第一次调用时才会检查。换句话说,如果Bean不存在,< idref>能在启动程序的时候就抛出错误,而< ref>只会在运行中抛出错误。
3.12、设置destory-method销毁方法
有的对象(例如数据源,JDBC连接,输入输出流等)在使用完毕后需要执行close()方法释放资源。可以使用destory-method配置。Spring在注销这些资源时会调用destory-method里配置的方法。例如:
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
.....
</bean>
3.13、设置depends-on依赖对象
Spring默认按照配置文件里Bean配置的先后顺序实例化Bean,但有时候在实例化A对象之前需要先实例化后面的B对象。这时候可以使用depends-on,强制先实例化B对象。如:
<bean id="a" class="examples.A" depends-on="b"></bean>
<bean id="b" class="examples.B"></bean>
在实例化A的时候会检查B的实例是否存在,如果不存在,先实例化B
3.14、初始化方法init-method
与destory-method相反,有的对象在实例化后需要执行某些初始化代码,但这些初始化代码不能写在构造函数中。这时候可以把这部分初始化代码写在一个方法中,如init(),使用init-method属性,强制Spring执行该方法进行初始化,如:
4、属性自动装配autowire
为了防止配置文件过大,可以使用autowire属性
4.1、配置autowire自动装配
使用< bean>的autowire属性后,不需要再用< property name="" value="" />显示地设置该Bean的属性、依赖关系。Spring会根据反射,自动寻找符合条件的属性,设置到该Bean属性上。如果autowire设置为byType,将会按照属性的类型自动匹配。如:
4.2、autowire取值范围
autowire属性定义的不是需要自动装配的属性名,而是自动装配的规则。一但配置,所有的属性都将遵循autowire定义的规则。autowire所有的取值以及意义见下表
取值 | 说明 |
---|---|
no | (默认)不采用autowire机制.。这种情况,当我们需要使用依赖注入,只能用< ref/>标签。 |
byName | 通过属性的名称自动装配(注入)。Spring会在容器中查找名称与bean属性名称一致的bean,并自动注入到bean属性中。当然bean的属性需要有setter方法。例如:bean A有个属性master,master的setter方法就是setMaster,A设置了autowire=“byName”,那么Spring就会在容器中查找名为master的bean通过setMaster方法注入到A中。 |
byType | 通过类型自动装配(注入)。Spring会在容器中查找类(Class)与bean属性类一致的bean,并自动注入到bean属性中,如果容器中包含多个这个类型的bean,Spring将抛出异常。如果没有找到这个类型的bean,那么注入动作将不会执行。 |
constructor | 类似于byType,但是是通过构造函数的参数类型来匹配。假设bean A有构造函数A(B b, C c),那么Spring会在容器中查找类型为B和C的bean通过构造函数A(B b, C c)注入到A中。与byType一样,如果存在多个bean类型为B或者C,则会抛出异常。但时与byType不同的是,如果在容器中找不到匹配的类的bean,将抛出异常,因为Spring无法调用构造函数实例化这个bean。 |
default | 采用父级标签(即beans的default-autowire属性)的配置。 |
如果显示定义了< property>或者< constructor-arg>,会覆盖默认装配。自动装配一般与下面的依赖检查连用。
注意:在大型项目中不推荐使用,因为自动装配会隐藏依赖装配的细节。降低可读性与可维护性,并可能带来意想不到的麻烦。
5、依赖检查dependency
有时候某些Bean的属性配置有错误,比如某个属性没有设置。这种错误在程序启动的时候不会有任何异常表现,会一直潜伏到Spring调用该Bean时才会被发现。为了防止这种情况,Spring提供依赖检查,在程序启动的时候检查依赖配置。如果有错误,启动时就会抛出异常,以便发现配置错误。
5.1、配置dependency依赖检查
依赖检查能够检查属性是否被设置。如果配置了依赖检查,程序启动时会进行配置校验,以便及时地发现配置错误。通过设置的dependency-check设置依赖检查规则,如:
5.2、dependency属性取值范围
dependency属性有多种取值,分别应对不同的情况。但是需要注意,dependency依赖检查是很生硬的,例如设置为object,将会检查所有的java对象属性,只要有一个属性没有设置,就会抛出异常,即某属性明明不需要设置,但是没法避免dependency检查,容易造成“一竿子全打死”的现象。dependency的取值以及意义见表
取值 | 说明 |
---|---|
no 或 default | 不做任何检查 |
simple | 仅检查基本类型,集合属性。如果属性没有设置,会抛出异常。 |
object | 仅检查Java对象属性。如果有属性没设置,会抛出异常。 |
all | 检查所有属性,等同于simple与object的并集 |
6、Bean的高级特性
Spring程序中,JAVA Bean一般与Spring是非耦合的,不会依赖于Spring类库。这也是Spring的优点。但有时候Java Bean需要知道自己在Spring框架中的一些属性。Spring提供了一些接口,实例化Java Bean对象后Spring会调用接口的方法。
6.1、BeanNameAware接口获取Bean的id
BeanNameAware接口帮助Java Bean知道自己在配置文件中的id,实现BeanNameAware,实现方法名为setBeanName()方法,初始化该对象后Spring就会执行该回调方法,将id设置进来。Bean中设置一个变量,接受id名称即可,例如:
package com.wht.spring.example;
import org.springframework.beans.factory.BeanNameAware;
public class WhatsTheNameBean implements BeanNameAware {
private String beanName;
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
提示:setBeanName()方法的回调发生在所有参数被设置完之后,初始化方法(init-method属性)被执行之前。
6.2、BeanFactoryAware接口获取BeanFactory
BeanFactoryAware接口帮助java Bean知道哪个BeanFactory实例化了自己,BeanFactoryAware接口中有setBeanFactory的回调方法,初始化该对象后,会回调该方法,将BeanFactory传递进来。BeanFactoryAware接口的代码如下:
public interface BeanFactoryAware{
void setBeanFactory(BeanFactory beanFactory) throws BeanException
}
用法同BeanNameAware,实现了BeanFactoryAware接口的Java Bean能够获取到BeanFactory,从BeanFactory中能够获取到BeanFactory中配置的其他Java Bean。Spring不推荐这样做,因为这样会与Spring耦合。获取其它Java Bean一般通过设置getter、setter方法,用依赖注入实现
6.3、InitializingBean接口执行初始化方法
实现了InitializingBean接口的Java Bean会在实例后、所有属性被设置后调用初始化方法。但使用该接口会与Spring代码发生耦合,因此不推荐使用。InitializingBean接口代码如下:
public interface InitializingBean{
public void afterPropertiesSet();
}
Spring推荐使用init-method配置,效果等价:
6.4、BeanFactory高级特性
如果Java Bean实现了BeanFactoryAware接口,就能够获得BeanFactory对象。BeanFactory有下面几个常用的方法如下,见名知意。
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String var1) throws BeansException;
<T> T getBean(String var1, @Nullable Class<T> var2) throws BeansException;
Object getBean(String var1, Object... var2) throws BeansException;
<T> T getBean(Class<T> var1) throws BeansException;
<T> T getBean(Class<T> var1, Object... var2) throws BeansException;
boolean containsBean(String var1);
boolean isSingleton(String var1) throws NoSuchBeanDefinitionException;
boolean isPrototype(String var1) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String var1, ResolvableType var2) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String var1, @Nullable Class<?> var2) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String var1) throws NoSuchBeanDefinitionException;
String[] getAliases(String var1);
7、属性覆盖器
对于一些参数,更实用更简单的方法是使用properties配置,而不是配置在Spring的配置文件中。Spring提供属性替代配置,允许把某些属性配置在properties文件中。
7.1、配置PropertyOverrideConfigurer属性覆盖器
PropertyOverrideConfigurer允许把XML配置里的某些参数配置到properties文件中。这在数据库配置中很常见。配置时需要配置一个PropertyOverrideConfigurer对象,指定properties文件的位置,然后把替换的属性用形如${jdbc.url}的字符串替代,如:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
PropertyOverrideConfigurer对象会到指定名称的properties文件(例如jdbc.properties)中,寻找属性名为变量的配置,{}中最好不要有空格
7.2、properties配置
具体的数据库配置是写在jdbc.properties里面的。properties中的配置比applicationContext.xml中更便于阅读、修改与维护。代码如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dev?characterEncoding=UTF-8
jdbc.username=root
jdbc.password="admin
这个是目前真实性项目常用的方式,进一步说,这个配置还是在配置文件中,而是通过SDK加载中央配置库的加密配置。
回到首页☞