spering getBean(),IOC
IOC:前面都是对bean定义的处理,postProcess已经实例化了。
解析bean的时候,把需要依赖注入的字段和方法,在postProcessMergedBeanDefinition方法中加到AutowiredAnnotationBeanPostProcessor的变量中,然后在AutowiredAnnotationBeanPostProcessor的作为入口,去依赖注入字段和方法。 protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); // 实例化一个转换器ConversionService
}
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName); // 没用,
}
beanFactory.preInstantiateSingletons(); //IOC
} public void preInstantiateSingletons() throws BeansException {
List<String> beanNames;
synchronized (this.beanDefinitionMap) { //所有的beanDefinition,也就是bean的定义信息
beanNames = new ArrayList<String>(this.beanDefinitionNames); //所有的bean的名字
}
for (String beanName : beanNames) {//实例化所有的bean
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 合并功能,父子合并了的。
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //不是抽象的,不是懒加载的,是单利,才会去实例化。
if (isFactoryBean(beanName)) {//实现了FactoryBean接口
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {//实现了SmartFactoryBean接口
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit(); //调用这个bean的isEagerInit方法,返回true就实例化,
}
}, getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit()); //调用这个bean的isEagerInit方法,返回true就实例化,
}
if (isEagerInit) {//返回true就实例化,
getBean(beanName); //实例化
}
}
else {//没有实现了FactoryBean接口,
getBean(beanName);
}
}
}
} 解析有父类的bean,就是合并子类和父类的信息,涉及到子类覆盖父类。 protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName); // 先从缓存中拿
if (mbd != null) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
} <bean id="parent" class="com.zhuguang.jack.testbean.Parent" abstract="true">
</bean>
<bean id="son" class="com.zhuguang.jack.testbean.Son" parent="parent">
</bean> 父类是用来继承的公共部分,不会被实例化。 protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, BeanDefinition containingBd)throws BeanDefinitionStoreException {//beanName是bean的名字,bd是bean的定义 synchronized (this.mergedBeanDefinitions) { //mergedBeanDefinitions 是缓存,
RootBeanDefinition mbd = null;
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
if (bd.getParentName() == null) { // bean没有父类,直接初始化一个RootBeanDefinition
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); //也是调用 new RootBeanDefinition(bd);
}
else {
mbd = new RootBeanDefinition(bd);//bd是bean的定义信息,mbd是子类,bd是父类,这里做一个拷贝,是为了不污染db,而是使用重新初始化的mbd。
}
}
else {
// bean有父类,要加载父类的信息
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName()); //获取父亲的名字,
if (!beanName.equals(parentBeanName)) { //跟父的名字不一样,
pbd = getMergedBeanDefinition(parentBeanName); //父类的bean定义,父类在有父类继续调用。
}
}
mbd = new RootBeanDefinition(pbd); //pbd是父类,构造父类
mbd.overrideFrom(bd);//bd是bean的定义信息,mbd是父类,bd是子类,子类覆盖父类的信息,
} if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) {
this.mergedBeanDefinitions.put(beanName, mbd); //加到缓存
}
}
return mbd;
}
} getBean(beanName); 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; //单利缓存中获取
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
if (isPrototypeCurrentlyInCreation(beanName)) {//已经创建了
throw new BeanCurrentlyInCreationException(beanName);
} BeanFactory parentBeanFactory = getParentBeanFactory();//父类容器,从父类容器获取bean。
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
String nameToLookup = originalBeanName(name);
if (args != null) {
return (T) parentBeanFactory.getBean(nameToLookup, args);;//父类容器,从父类容器获取bean。
}
else {
return parentBeanFactory.getBean(nameToLookup, requiredType);;//父类容器,从父类容器获取bean。
}
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);//父子合并 String[] dependsOn = mbd.getDependsOn();//依赖的bean,创建这个bean的时候先要创建哪些bean,
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {//没有依赖关系
throw new BeanCreationException("Circular depends-on relationship between '" +
beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);//增加依赖关系,
getBean(dependsOnBean);//先实例化依赖的bean
}
} if (mbd.isSingleton()) {//单利
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
}
});
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 '" + 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);
}
}
}
} if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
}
return (T) bean;
} 单利:
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
}
}); public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
synchronized (this.singletonObjects) {//缓存
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
try {
singletonObject = singletonFactory.getObject(); //createBean
}
addSingleton(beanName, singletonObject);//缓存
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
} protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)throws BeanCreationException {
resolveBeanClass(mbd, beanName); //bean的定义,bean的名字,拿出beanClass,
try {
mbd.prepareMethodOverrides();
}
try {
Object bean = resolveBeforeInstantiation(beanName, mbd);//BeanPostProcessors已经实例化了,实例化之前插一脚,直接返回这个实例化的bean。后面不用走了。可以自己去实例化这个bean,spring就不会管这个bean的实例化了。下面有梨子InstantiationAwareBeanPostProcessorTest,
if (bean != null) {
return bean;
}
}
//前面resolveBeforeInstantiation没有成功实例化出这个bean。spring来实例化这个bean。
Object beanInstance = doCreateBean(beanName, mbd, args);
return beanInstance;
} protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); //先执行before在执行after方法,
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
} protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)throws BeansException {
for (BeanPostProcessor bp : getBeanPostProcessors()) { //取出所有的BeanPostProcessors,
if (bp instanceof InstantiationAwareBeanPostProcessor) { // 实现InstantiationAwareBeanPostProcessor接口的自己写的类,可以自己去实例化这个bean,spring就不会管这个bean的实例化了。下面有梨子InstantiationAwareBeanPostProcessorTest,
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); //通过所有的BeanPostProcessors来返回这个实例化的bean。spring就不会管这个bean的实例化了。
if (result != null) {
return result;
}
}
}
return null;
} public class InstantiationAwareBeanPostProcessorTest implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
try {
return beanClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
} protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);//缓存,
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args); // 包装类,通过反射实例创建完成。但是实例的属性还没有操作。不包括IOC的依赖注入。属性是没有值的。
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //下面解析,
//解析完这个类需要依赖注入的字段和方法之后,在AutowiredAnnotationBeanPostProcessor增加一行记录factoryBeanTest=[FactoryBeanTest.woman(依赖注入字段), FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)(依赖注入方法)]。
}
mbd.postProcessed = true;
}
} boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); // 是单利并且允许循环依赖,
if (earlySingletonExposure) {
addSingletonFactory(beanName, new ObjectFactory<Object>() {//把ObjectFactory这个匿名对象加入到spring的三级缓存,在getSingleton从缓存取的时候,会调用三级缓存中的匿名对象ObjectFactory的getObject() 。
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
} Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper); //IOC,依赖注入8中类型,
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
} if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,");
}
}
}
} try {
registerDisposableBeanIfNecessary(beanName, bean, mbd); //注册,
} return exposedObject;
} protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
Class<?> beanClass = resolveBeanClass(mbd, beanName);//拿到bean的class,class com.zhuguang.jack.testbean.A,
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args); //自己写的类去初始化,不要spring实例化,
}
return instantiateBean(beanName, mbd);
}
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) { //代码执行权限,
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
return getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
}, getAccessControlContext());
}
else {
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); //通过反射,com.zhuguang.jack.testbean.A@5226e402实例创建完成。
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance); //包装,
initBeanWrapper(bw);
return bw;
}
} public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
if (beanDefinition.getMethodOverrides().isEmpty()) {
synchronized (beanDefinition.constructorArgumentLock) {
constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = beanDefinition.getBeanClass(); //拿到需要实例化的类,
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null); //拿到构造器,无参构造器,为了防止循环依赖问题。
}
});
}
}
}
}
return BeanUtils.instantiateClass(constructorToUse);//反射,实例化bean,
}
else {
return instantiateWithMethodInjection(beanDefinition, beanName, owner);//Cglib
}
} protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)throws BeansException {
try {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {//实现这个接口的bean,才能做处理,
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; // 有一个AutowiredAnnotationBeanPostProcessor,
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
} AutowiredAnnotationBeanPostProcessor类的:依赖注入可以通过配置文件,也可以通过注解@Autowired,@Autowired,可以加载属性上面,也可以加载set方法上面。
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (beanType != null) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType); //返回这个类,需要注解依赖注入的属性和方法,
metadata.checkConfigMembers(beanDefinition);
}
} private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz) {
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); //AutowiredAnnotationBeanPostProcessor的缓存,
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
metadata = buildAutowiringMetadata(clazz); //返回这个类,需要注解依赖注入的属性和方法,
this.injectionMetadataCache.put(cacheKey, metadata); //解析完这个类需要依赖注入的字段和方法之后,在AutowiredAnnotationBeanPostProcessor增加一行记录factoryBeanTest = [ FactoryBeanTest.woman, FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],this=AutowiredAnnotationBeanPostProcessor。
}
}
}
return metadata;
}
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
Class<?> targetClass = clazz; do {
LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); //InjectedElement是反射的属性或者方法对象,
//@Autowired加载属性上面,
for (Field field : targetClass.getDeclaredFields()) { // 拿到类的所有属性,
AnnotationAttributes annotation = findAutowiredAnnotation(field); //获取字段的Autowired,Value,Inject 3种注解,其余注解不管,返回映射关系,
if (annotation != null) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
boolean required = determineRequiredStatus(annotation);//拿到注解的值,
currElements.add(new AutowiredFieldElement(field, required)); //一个字段field对应一个AutowiredFieldElement,装到容器中。还没有涉及到IOC过程。
}
}
//@Autowired加载set方法上面,
for (Method method : targetClass.getDeclaredMethods()) { // 拿到类的所有方法,有注解的方法是 FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)。
@Autowired
public void setWoman(Woman woman) {
this.woman = woman;
},
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); //方法的重载
AnnotationAttributes annotation = BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod) ?
findAutowiredAnnotation(bridgedMethod) : findAutowiredAnnotation(method); //找到这个方法上面有没有Autowired,Value,Inject 3种注解,其余注解不管,
if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
boolean required = determineRequiredStatus(annotation);//拿到注解的值,
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);//拿到方法的类型对象PropertyDescriptor
currElements.add(new AutowiredMethodElement(method, required, pd));//把method, required, pd包装成AutowiredMethodElement放到容器currElements中去,
}
}
elements.addAll(, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class); //父类,也去解析父类,
return new InjectionMetadata(clazz, elements); //返回这个类,需要注解依赖注入的属性和方法,
} public AutowiredAnnotationBeanPostProcessor() { //AutowiredAnnotationBeanPostProcessor里面加了Autowired,Value,Inject 3种注解,
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
ClassLoader cl = AutowiredAnnotationBeanPostProcessor.class.getClassLoader();
this.autowiredAnnotationTypes.add((Class<? extends Annotation>) cl.loadClass("javax.inject.Inject"));
} singletonObjects是一级缓存,一个bean依赖注入完成之后,属性都完成了,才会存在在singletonObjects这个Map里面。
earlySingletonObjects是二级缓存,一个bean还没有完全实例化,有可能里面还有一些属性,还没有完全依赖注入完。
singletonFactories是三级缓存,里面存的是ObjectFactory对象。 二级三级缓存,就是为了解决循环依赖问题,A里面有B,B里面有A。A实例化的时候B没有实例化,此时A还是一个空壳子,会加到三级缓存,然后getBean(B),B实例化的时候发现有属性A,会去实例化getBean(A),此时A在三级缓存中,会调用这个三级缓存的getObject()方法。 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(); //三级缓存调用getObject(),
this.earlySingletonObjects.put(beanName, singletonObject);//移到二级缓存,
this.singletonFactories.remove(beanName);//从三级缓存删除,
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
} protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {//一级缓存没有
this.singletonFactories.put(beanName, singletonFactory);//放入三级缓存,准备上面的,调用三级缓存的getObject(),
this.earlySingletonObjects.remove(beanName);//二级缓存移除
this.registeredSingletons.add(beanName);
}
}
} protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { //这个接口,
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
if (exposedObject == null) {
return exposedObject;
}
}
}
}
return exposedObject;
} protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues(); //拿到factoryBeanTest的需要依赖注入的属性,PropertyValues: length=1; bean property 'woman'
boolean continueWithPropertyPopulation = true; //当前bean的依赖注入到底要不要做,
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) { //
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { //返回布尔值,当前bean的依赖注入要不要做,
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) { //为false,当前bean的依赖注入就不用做了,
return;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //有没有实现InstantiationAwareBeanPostProcessor接口,
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) { //找到这个接口的类,包括spring的和自己的,
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);//@Autoware,@Value的依赖注入。 AutowiredAnnotationBeanPostProcessor类的postProcessPropertyValues方法,依赖注入在这里。
if (pvs == null) {
return;
}
}
}
}
}
applyPropertyValues(beanName, mbd, bw, pvs); //通过xml依赖注入,
} AutowiredAnnotationBeanPostProcessor类:
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass()); //从缓存取,需要依赖注入的字段和方法,[FactoryBeanTest.woman, .FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],
try {
metadata.inject(bean, beanName, pvs);//依赖注入在这里。
}
return pvs;
} public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
Collection<InjectedElement> elementsToIterate = (this.checkedElements != null ? this.checkedElements : this.injectedElements); //[FactoryBeanTest.woman, FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
element.inject(target, beanName, pvs); //目标对象FactoryBeanTest@5d39f2d8,bean名字factoryBeanTest,需要依赖注入的字段或者方法[bean property 'woman'] 。依赖注入在这里。
}
}
} //依赖注入字段。依赖注入在这里。
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
Field field = (Field) this.member; //FactoryBeanTest.woman
try {
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<String>();
TypeConverter typeConverter = beanFactory.getTypeConverter();
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);//拿到依赖注入的属性的值,com.zhuguang.jack.testbean.Woman@abbc908。
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
}
this.cached = true;
}
}
}
if (value != null) {//com.zhuguang.jack.testbean.Woman@abbc908,
ReflectionUtils.makeAccessible(field);
field.set(bean, value); //字段设置值
}
}
}
} public Object resolveDependency(DependencyDescriptor descriptor, String beanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
else {
if (result == null) {
result = doResolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
}
return result;//com.zhuguang.jack.testbean.Woman@abbc908。
}
} public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class<?> type = descriptor.getDependencyType(); //class com.zhuguang.jack.testbean.Woman
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
} if (type.isArray()) { //依赖注入的是数组
Class<?> componentType = type.getComponentType();
DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
targetDesc.increaseNestingLevel();
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, targetDesc);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor);
}
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
Object result = converter.convertIfNecessary(matchingBeans.values(), type);
if (this.dependencyComparator != null && result instanceof Object[]) {
Arrays.sort((Object[]) result, this.dependencyComparator);
}
return result;
}
else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { //依赖注入的是集合
Class<?> elementType = descriptor.getCollectionType();
if (elementType == null) {
if (descriptor.isRequired()) {
throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]");
}
return null;
}
DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
targetDesc.increaseNestingLevel();
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, targetDesc);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor);
}
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
Object result = converter.convertIfNecessary(matchingBeans.values(), type);
if (this.dependencyComparator != null && result instanceof List) {
Collections.sort((List<?>) result, this.dependencyComparator);
}
return result;
}
else if (Map.class.isAssignableFrom(type) && type.isInterface()) { //依赖注入的是MAp
Class<?> keyType = descriptor.getMapKeyType();
if (keyType == null || !String.class.isAssignableFrom(keyType)) {
if (descriptor.isRequired()) {
throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
"] must be assignable to [java.lang.String]");
}
return null;
}
Class<?> valueType = descriptor.getMapValueType();
if (valueType == null) {
if (descriptor.isRequired()) {
throw new FatalBeanException("No value type declared for map [" + type.getName() + "]");
}
return null;
}
DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
targetDesc.increaseNestingLevel();
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, targetDesc);
if (matchingBeans.isEmpty()) {
if (descriptor.isRequired()) {
raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
}
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
return matchingBeans;
}
else { //依赖注入不是数组,不是Map,不是集合,是基本类型或者对象,
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); //{woman=com.zhuguang.jack.testbean.Woman@9a7a808},从bean工厂获取,最终还是通过getBean()方法获取。
if (matchingBeans.size() > ) {//依赖注入的类有多个,报错。
String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor);
if (primaryBeanName == null) {
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(primaryBeanName);
}
return matchingBeans.get(primaryBeanName);
}
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
if (autowiredBeanNames != null) {
autowiredBeanNames.add(entry.getKey());
}
return entry.getValue();//woman=com.zhuguang.jack.testbean.Woman@abbc908
}
} protected Map<String, Object> findAutowireCandidates(
String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { for (String candidateName : candidateNames) {
if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) {
result.put(candidateName, getBean(candidateName)); //还是通过getBean()方法获取需要依赖注入的属性的值,
}
}
return result;
} //方法的依赖注入,依赖注入在这里。通过反射给方法设置值,形参通过getBean()方法获取。
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
else {
Object arg = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
if (arg == null && !this.required) {
arguments = null;
break;
}
arguments[i] = arg;
}
}
if (arguments != null) {
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments); //通过反射给方法设置值,形参通过getBean()方法获取。
}
}
} 上main是通过注解的依赖注入,还有通过XML的依赖注入。 protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { //通过xml依赖注入, MutablePropertyValues mpvs = null;
List<PropertyValue> original; if (System.getSecurityManager() != null) {
if (bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
} if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
try {
bw.setPropertyValues(mpvs);
return;
}
}
original = mpvs.getPropertyValueList(); //[bean property 'woman'],需要xml依赖注入的属性,
}
else {
original = Arrays.asList(pvs.getPropertyValues()); //[bean property 'woman'],需要xml依赖注入的属性,
} TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
else {
String propertyName = pv.getName();//woman,
Object originalValue = pv.getValue();//<woman>,RuntimeBeanReference类型,
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); //beanFactory.getBean(refName);从bean工厂拿。因为依赖注入的属性有可能是一个引用,有可能是一个字符串需要转换成时间,
Object convertedValue = resolvedValue; //com.zhuguang.jack.testbean.Woman@9a7a808,
boolean convertible = bw.isWritableProperty(propertyName) &&!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);//com.zhuguang.jack.testbean.Woman@9a7a808,类型转换之后的值。上面的valueResolver.resolveValueIfNecessary(pv, originalValue)有可能转换还不够,还需要转换,
}
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue)); //pv, convertedValue一个是原始属性值,一个是转换之后的值。封装成PropertyValue,
}
}
} try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy)); //设置值,MutablePropertyValues才是需要真正设置的值。
}
} public void setPropertyValue(PropertyValue pv) throws BeansException {
PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
if (tokens == null) {
String propertyName = pv.getName();
BeanWrapperImpl nestedBw;
try {
nestedBw = getBeanWrapperForPropertyPath(propertyName);
}
tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
if (nestedBw == this) {
pv.getOriginalPropertyValue().resolvedTokens = tokens;
}
nestedBw.setPropertyValue(tokens, pv);
}
else {
setPropertyValue(tokens, pv);
}
} protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
else {
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
invokeInitMethods(beanName, wrappedBean, mbd);
} if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
} public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException { Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
} private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
} protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
else {
((InitializingBean) bean).afterPropertiesSet(); //实例化bean的时候,调用afterPropertiesSet()方法,没有参数,做资源的加载(redis,mongodb的加载,),一个bean只会调用一次。在bean实例化之后,IOC之后调用。
}
} if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
} protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
String initMethodName = mbd.getInitMethodName(); //拿到init方法的名称,init-method,
final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); //反射得到这个方法,
else {
try {
ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean); //调用,
}
}
} protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) { //单利,就缓存,
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
} public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
spering getBean(),IOC的更多相关文章
- Spring IoC,IoC原理
一.IoC概念及原理 IOC的别名:依赖注入(DI) 2004年,Martin Fowler探讨了同一个问题,既然IOC是控制反转,那么到底是“哪些方面的控制被反转了呢?”,经过详细地分析和论证后,他 ...
- Spring,IOC源码分析
有错勿喷 1.首先是Spring,IOC的基本概念 IOC是一个容器 容器启动的时候创建所有单实例对象 我们可以直接从容器中获取到这个对象 2.调试流程 ioc容器的启动过程?启动期间都做了什么(什么 ...
- Atitit。如何实现dip, di ,ioc ,Service Locator的区别于联系
Atitit.如何实现dip, di ,ioc ,Service Locator的区别于联系 1. Dip原则又来自于松耦合思想方向1 2. 要实现dip原则,有以下俩个模式1 3. Ioc和di的 ...
- Xwork概况 XWork是一个标准的Command模式实现,并且完全从web层脱离出来。Xwork提供了很多核心功能:前端拦截机(interceptor),运行时表单属性验证,类型转换,强大的表达式语言(OGNL – the Object Graph NavigationLanguage),IoC(Inversion of Control反转控制)容器等。 ----------------
Xwork概况 XWork是一个标准的Command模式实现,并且完全从web层脱离出来.Xwork提供了很多核心功能:前端拦截机(interceptor),运行时表单属性验证,类型转换,强大的表达式 ...
- 【开发者笔记】揣摩Spring-ioc初探,ioc是不是单例?
前言: 控制反转(Inversion of Control,英文缩写为IoC)把创建对象的权利交给框架,是框架的重要特征,并非面向对象编程的专用术语.它包括依赖注入(Dependency Inject ...
- 什么是AOP和OOP,IOC和DI有什么不同?
什么是AOP和OOP,IOC和DI有什么不同? 解答: 1)面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)是一种计算机编程架构.AOP是OOP的延续, ...
- 自己实现IOC容器,java代码实现简易版IOC容器,IOC容器实现的步骤分解
一.需求 实现一个简易的IOC容器,管理Bean,从IOC容器的BeanFactory中获取实例,从而取代自己new实例的做法. 二.实现步骤分析 三.具体代码实现 自定义注解类 MyComponen ...
- Autofac 的属性注入,IOC的坑
Autofac 是一款优秀的IOC的开源工具,完美的适配.Net特性,但是有时候我们想通过属性注入的方式来获取我们注入的对象,对不起,有时候你还真是获取不到,这因为什么呢? 1.你对Autofac 不 ...
- Laravel 服务容器,IoC,DI
DI DI 就是常说的依赖注入,那么究竟什么是依赖注入呢? 打个比方,电脑(非笔记本哈)需要键盘和鼠标我们才能进行操作,这个‘需要’换句话说就是‘依赖’键盘和鼠标. 那么,相应的,一个类需要另一个类才 ...
随机推荐
- yield return,yield break
转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...
- 网格弹簧质点系统模拟(Spring-Mass System by Fast Method)附源码(转载)
转载: https://www.cnblogs.com/shushen/p/5311828.html 弹簧质点模型的求解方法包括显式欧拉积分和隐式欧拉积分等方法,其中显式欧拉积分求解快速,但积分步长 ...
- HTML 使用表格制作简单的个人简历
复习一下HTML,用表格做一个简单的个人简历 <!DOCTYPE html> <html> <head> <meta charset="utf-8& ...
- Mysql EF Core 快速构建 Web Api
(1)首先创建一个.net core web api web项目; (2)因为我们使用的是ef连接mysql数据库,通过NuGet安装MySql.Data.EntityFrameworkCore,以来 ...
- iOS开发 简单实现视频音频的边下边播 (转)
1.ios视频音频边缓存边播放,缓存时可以在已下载的部分拖拽进度条. 3.无论是下载到一半退出还是下载完退出,已缓存的数据都存到自己指定的一个路径.如果已下载完,下次播放时可以不再走网络,直接播放 ...
- 电信NBIOT 5 - NB73模块下行测试(自己平台-电线平台-NB73)
电信NBIOT 1 - 数据上行(中国电信开发者平台对接流程) 电信NBIOT 2 - 数据上行(中间件获取电信消息通知) 电信NBIOT 3 - 数据下行 电信NBIOT 4 - NB73模块上行测 ...
- 团队作业第3周——需求改进&系统设计
目录 团队作业第3周--需求改进&系统设计 1.需求&原型改进 2.系统设计 3.Alpha任务分配计划 4.测试计划 1 测试术语 4.2 有关项目人员组成 2 任务概述 3.测试策 ...
- HeadFirst设计模式---装饰者
定义装饰者模式 装饰者模式动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案.这句话摘自书中,给人读得很生硬难懂.通俗地来说,装饰者和被装饰者有相同的父类,装饰者的行为组装着 ...
- 一条SELECT查询语句在数据库里执行时都经历了什么
每天都在跟 mysql 打交道,你知道执行一条简单的 select 语句,都经历了哪些过程吗? 首先,mysql 主要是由 server 层和存储层两部分构成的.server 层主要包括连接器.查询缓 ...
- 曹玉中-201871010105《面向对象程序设计(java)》第6-7周学习总结
曹玉中-201871010105<面向对象程序设计(java)>第6-7周学习总结 项目 内容 这个作业属于哪个课程 <任课教师博客主页链接> https://www.c ...