摘要:简单介绍模块和模块是框架的基础部分,提供控制反转和依赖注入特性。
Spring Framework简单介绍
Core Container模块:Core 和 Beans 模块是框架的基础部分,提供 IoC (控制反转)和 DI(依赖注入)特性。 Context构建于Core 和 Bean 之上,提供了一个BeanFactory来访问应用组件,添加了国际化(例如资源绑定)、事件传播、资源加载等。SpEL提供了强大的表达式语言。
Data Access/Integration模块:JDBC提供了一个JDBC抽象层,ORM对象关系映射如:JPA,XOM提供了一个ObjectXML映射关系,JMS提供了生产消息和消费消息的功能,Transactions:提供了编程和声明性的事务管理,这些事务类必须实现特定的接口。
Web模块:提供了面向Web的特性,比如Spring Mvc,使用servlet listeners初始化IoC容器以及一个面向Web的应用上下文,典型的父子容器关系。
Aop模块:Aspects模块提供了对AspectJ集成的支持。Instrumentation模块提供了class instrumentation支持和classloader实现,动态字节码插桩。
Test模块:Test模块支持使用Junit等对Spring组件进行测试
Ioc的核心思想以及常用注解和应用
Ioc的核心思想:资源组件不由使用方管理,而由不使用资源的第三方管理,这可以带来很多好处。第一,资源集中管理,实现资源的可配置和易管理。第二,降低了使用资源双方的依赖程度,也就是我们说的耦合度
常用的注解:
@Configuration 相对于配置文件中的
@Bean 相对于配置文件中的
@CompentScan 包扫描
@Scope 配置Bean的作用域
@Lazy 是否开启懒加载
@Conditional 条件注解 spring boot中经常用到
@Import 导入组件
......
应用:
package com.toby.ioc.iocprinciple;
import org.springframework.beans.factory.annotation.Autowired;
public class PrincipleAspect {
@Autowired
private PrincipleLog principleLog;
/*public PrincipleLog getPrincipleLog() {
return principleLog;
}
public void setPrincipleLog(PrincipleLog principleLog) {
this.principleLog = principleLog;
}*/
}
package com.toby.ioc.iocprinciple;
public class PrincipleBean {
}
package com.toby.ioc.iocprinciple;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan(basePackages = {"com.toby.ioc.iocprinciple"})
//@ImportResource("classpath:Beans.xml")
@Import(PrincipleService.class)
public class PrincipleConfig {
@Bean
public PrincipleBean principleBean(){
return new PrincipleBean();
}
//@Bean(autowire = Autowire.BY_TYPE)
@Bean
public PrincipleAspect principleAspect(){
return new PrincipleAspect();
}
@Bean
@Primary
public PrincipleLog principleLog(){
return new PrincipleLog();
}
@Bean
public PrincipleLog principleLog2(){
return new PrincipleLog();
}
}
package com.toby.ioc.iocprinciple;
import org.springframework.stereotype.Controller;
@Controller
public class PrincipleController {
}
package com.toby.ioc.iocprinciple;
import org.springframework.stereotype.Repository;
@Repository
public class PrincipleDao {
}
package com.toby.ioc.iocprinciple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @desc: 循环依赖
* @author: toby
*/
@Component
public class PrincipleInstanceA {
@Autowired
private PrincipleInstanceB instanceB;
}
package com.toby.ioc.iocprinciple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @desc: 循环依赖
* @author: toby
*/
@Component
public class PrincipleInstanceB {
@Autowired
private PrincipleInstanceA instanceA;
}
package com.toby.ioc.iocprinciple;
/**
* @desc:
* @author: toby
*/
public class PrincipleLog {
}
package com.toby.ioc.iocprinciple;
/**
* @desc:
* @author: toby
*/
public class PrincipleService {
}
package com.toby.ioc.iocprinciple;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @desc: ioc原理解析 启动
* @author: toby
*/
public class PrincipleMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrincipleConfig.class);
/*for (String beanDefinitionName : context.getBeanDefinitionNames()) {
System.out.println("bean定义名称:" + beanDefinitionName);
}*/
PrincipleAspect principleAspect = context.getBean(PrincipleAspect.class);
context.close();
System.out.println(principleAspect);
}
}
完整的代码请见:spring
getBean的源码解析
beanfactory的类继承图:
首先创建org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(java.lang.Class...)
public AnnotationConfigApplicationContext(Class... annotatedClasses) {
//主要的作用往容器中注册系统级别的处理器,为处理我们自定义的配置类准备,以及初始化classpath下的bean定义扫描
this();
//注册我们自定义的配置类
register(annotatedClasses);
//Ioc容器刷新12大步
refresh();
}
org.springframework.context.support.AbstractApplicationContext#refresh 12大步
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//1:准备刷新上下文环境
prepareRefresh();
//2:获取初始化Bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//3:对bean工厂进行填充属性
prepareBeanFactory(beanFactory);
try {
//4:Spring开放接口 留给子类去实现该接口
postProcessBeanFactory(beanFactory);
//:5:调用我们的bean工厂的后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// 6:注册我们bean后置处理器
registerBeanPostProcessors(beanFactory);
// 7:初始化国际化资源处理器
initMessageSource();
//8:初始化事件多播器
initApplicationEventMulticaster();
//9:// 这个方法同样也是留个子类实现的springboot也是从这个方法进行启动tomcat的.
onRefresh();
//10:把我们的事件监听器注册到多播器上
registerListeners();
//11:实例化所有的非懒加载的单实例bean
finishBeanFactoryInitialization(beanFactory);
//12:最后刷新容器 发布刷新事件(Spring cloud eureka也是从这里启动的)
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset "active" flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring"s core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
第11步:实例化所有的非懒加载的单实例bean
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
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));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
//冻结所有的bean定义
beanFactory.freezeConfiguration();
//实例化剩余的非懒加载的单实例bean
beanFactory.preInstantiateSingletons();
}
实例化剩余的非懒加载的单实例bean:
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
// 获取容器中所有beanName
List beanNames = new ArrayList(this.beanDefinitionNames);
//触发实例化所有的非懒加载的单实例bean
for (String beanName : beanNames) {
//合并bean定义
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象,单实例,非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//是否工厂bean,是要获取factorybean的getObject方法
if (isFactoryBean(beanName)) {
//factorybean的bean那么前面加了一个FACTORY_BEAN_PREFIX就是&
final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Boolean run() {
return ((SmartFactoryBean) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean) factory).isEagerInit());
}
if (isEagerInit) {
//调用getBean流程
getBean(beanName);
}
}
else {//非工厂bean
//调用getBean流程
getBean(beanName);
}
}
}
//触发初始化之后的回调,到这里所有的bean都存放在了单例缓冲池中了
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction