Spring是一个极其复杂和庞大的项目,仅仅使用一篇或者几篇文章可能连XML的bean加载解析都难以讲完。而且写作本身就是一件非常费时费力的事情,所以在Spring探险专栏中,可能要花费几十篇的文章来讲解Spring。而且Spring错综复杂,各个点之间关联甚密,要梳理之间的关系,把它们层层剖解,也是非常困难的。
这篇文章是Spring探险专栏的第一篇文章。比较简短,主要是对Spring实现有一个简单的介绍。了解Spring中最基本管理和加载普通对象(注意是“普通对象”)是非常有意义的,也是了解Spring原理的第一步。
废话不多说了,先来看一看示例代码。这个示例代码是非常简单的实例代码,既不包含Spring是如何扫描和加载注解的,也不包含Spring动态的生成代理对象。
package Spring;
public interface IDemoService {
void add(int a, int b);
}
package Spring;
public class DemoServiceImpl implements IDemoService {
@Override
public void add(int a, int b) {
}
}
public class Main {
@SuppressWarnings("unused")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
IDemoService service = context.getBean(IDemoService.class);
service.add(1, 2);
if (service instanceof IDemoService) {
System.out.println("service is IDemoService Type");
}
if (service instanceof BeanFactory) {
System.out.println("service is BeanFactory Type");
}
if (service instanceof FactoryBean) {
System.out.println("service is FactoryBean Type");
}
}
BeanFactory 和FactoryBean是Spring框架中两个非常重要的核心类,稍后会讲到。这里列举出来只是让我们对Spring 这两个核心类有印象。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:lang="http://www.springframework.org/schema/lang" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="Spring"></context:component-scan>
<bean id="demoService" class="Spring.DemoServiceImpl">
</bean>
</beans>
结果只打印出了:
service is IDemoService Type
目前通过Spring得到的IDemoService对象还只是一个普通对象。与自己new出来的对象毫无二致。
BeanFactory与ApplicationContext:Spring IOC容器的基本规范
对于任意一个ApplicationConext而言,最终都发现继承了BeanFactory接口和ApplicationContext接口。
如果把IOC容器比作一个商家的水桶,那么BeanFactory定义了如何存储水,如何从水桶取出水等,就是纯粹的水桶。而ApplicationConext则为这个水桶加上附加价值,比如单价,颜色,外在形状,出产地等,商标,提手等,都是同样的水桶,但是不同的ApplicationContext提供不同的外在高级功能(比如提手不同,是吃水的水桶还是浇花的水壶)。它们之间通过代理的模式相关联。
BeanFactory的定义如下:
package org.springframework.beans.factory;
public interface BeanFactory {
/**
* 用来引用一个实例,或把它和工厂产生的Bean区分开,就是说,如果一个FactoryBean的名字为a,那么,$a会得到那个Factory
*/
String FACTORY_BEAN_PREFIX = "&";
/*
* 四个不同形式的getBean方法,获取实例
*/
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
boolean containsBean(String name); // 是否存在
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;// 是否为单实例
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;// 是否为原型(多实例)
boolean isTypeMatch(String name, Class<?> targetType)
throws NoSuchBeanDefinitionException;// 名称、类型是否匹配
Class<?> getType(String name) throws NoSuchBeanDefinitionException; // 获取类型
String[] getAliases(String name);// 根据实例的名字获取实例的别名
}
有两条主线来探究IOC容器:
一条是 BeanFactory的主线,只包含了类的生成与获取,比较重要,也是面试容易考到的地方;
一条是 ApplicationContext的主线,在beanfactory基础上添加了许多高级的特性,比如回调,高级注解等。(个人觉得,研究一个大项目的源码也需要按照不同的主线来梳理,要不然读起来毫无头绪)。
首先来看最重要的BeanFactory主线。
通过对ClassPathXmlApplicationContext的getBean方法的向上查找,其实际上是调用了DefaultListableBeanFactory中的getBean方法:
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
return getBean(requiredType, (Object[]) null);
}
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args);
if (namedBean != null) {
return namedBean.getBeanInstance();
}
BeanFactory parent = getParentBeanFactory();
if (parent != null) {
return parent.getBean(requiredType, args);
}
throw new NoSuchBeanDefinitionException(requiredType);
}
可以看的出来NamedBeanHolder 是对Bean对象的封装。NamedBeanHolder通过DefaultListableBeanFactory的resolveNamedBean方法得到:
@SuppressWarnings("unchecked")
private <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType, Object... args) throws BeansException {
Assert.notNull(requiredType, "Required type must not be null");
//candidateNames=["IDemoService"]
String[] candidateNames = getBeanNamesForType(requiredType);
if (candidateNames.length > 1) {
List<String> autowireCandidates = new ArrayList<String>(candidateNames.length);
for (String beanName : candidateNames) {
if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) {
autowireCandidates.add(beanName);
}
}
if (!autowireCandidates.isEmpty()) {
candidateNames = autowireCandidates.toArray(new String[autowireCandidates.size()]);
}
}
if (candidateNames.length == 1) {
String beanName = candidateNames[0];
return new NamedBeanHolder<T>(beanName, getBean(beanName, requiredType, args));
}
else if (candidateNames.length > 1) {
Map<String, Object> candidates = new LinkedHashMap<String, Object>(candidateNames.length);
for (String beanName : candidateNames) {
if (containsSingleton(beanName)) {
candidates.put(beanName, getBean(beanName, requiredType, args));
}
else {
candidates.put(beanName, getType(beanName));
}
}
String candidateName = determinePrimaryCandidate(candidates, requiredType);
if (candidateName == null) {
candidateName = determineHighestPriorityCandidate(candidates, requiredType);
}
if (candidateName != null) {
Object beanInstance = candidates.get(candidateName);
if (beanInstance instanceof Class) {
beanInstance = getBean(candidateName, requiredType, args);
}
return new NamedBeanHolder<T>(candidateName, (T) beanInstance);
}
throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet());
}
return null;
}
本实例的由于都是默认设置,所以别名只有一个。通过getBeanNamesForType得到别名,然后根据别名的数量来执行不同的逻辑。在本实例中,别名只有一个(IDemoService),所以代码会执行到如下的if条件中:
if (candidateNames.length == 1) {
String beanName = candidateNames[0];
return new NamedBeanHolder<T>(beanName, getBean(beanName, requiredType, args));
}
怎么每次都new了一个对象呢?那么一定是在getBean(beanName, requiredType, args)有问题。进入方法内部,发现这个方法是其父类的AbstractBeanFactory的方法,并最终来到了AbstractBeanFactory类的doGetBean方法中:
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
/**
* Spring 默认是懒加载,对于本实例,第一次获取肯定得到
* 空对象。会进入到else结构体的内部。
*/
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
// Create bean instance.
//getSingleton现在有值了。暂时忽略掉上面那一大段代码,createBean就是从XML文件中或者注解中间得到需要的bean对象!通过不同的配置(BeanDefinition对象)来不同的处理。
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
在得到sharedInstance对象之后,按理说只要返回这个对象就可以了,但Spring实际上并没有返回,而是再将sharedInstance作为参数传入到getObjectForBeanInstance方法中,来看看这个方法是什么内容:
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
在这个方法内部,可以看到如果sharedInstance对象不是FactoryBean的实例,就直接返回;否则就继续执行。分析这段代码可以发现,一个对象继承了FactoryBean接口,那么将会返回在FactoryBean中getObject()方法中定义的对象,而不是原生的sharedInstance对象。这就说明了只要通过继承FactoryBean接口,就可以动态的返回指定对象,而不是原生bean对象。如果需要对普通的对象作出一些改变,比如动态的从容器中获取针对同一个接口的不同实现,实现Spring与RPC调用的无缝连接等等一些需要特殊定制返回对象的地方。
BeanDefinition对象是什么
BeanDefinition可以看成是堆XML中<bean>标签的抽象。比如init-method,destory-method等等。这些xml标签统一的处理成了BeanDefinition对象,然后才能被IOC容器识别。不过其名字与<bean>标签中的名字不能一一对应,因为读取和设置值是分开的。在下一章中将细致讲解XML文件的读取和bean对象的创建。
getSingleton()方法
getSingleton是在DefaultSingletonBeanRegistry类中实现的。由于AbstractBeanFactory继承了FactoryBeanRegistrySupport,而FactoryBeanRegistrySupport又继承自DefaultSingletonBeanRegistry,所以在AbstractBeanFactory中可以直接调用getSingleton方法。其实现如下:
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
其中singletonObjects对象的声明是这样的:
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
这就说明了,Spring中对所有的对象都是采用ConcurrentHashMap来缓存的。
有什么问题或者建议,可以加入小密圈和我一起讨论,或者在简书留言,欢迎喜欢和打赏。
最后向大家安利一本关于Java并发不错的书:Java并发编程系统与模型,个人觉得写得不错,比较通俗易懂,非常适合初学者。