(3)spring源码解析-refresh()⽅法之前本⽂是作者原创,版权归作者所有.若要转载,请注明出处.
本⽂源码版本话不多说,开始
⾸先是配置类
@Configuration
@ComponentScan("com.day01")
public class SpringConfig {
}
IndexService
@Service
public class IndexService {
public IndexService(){
System.out.println("IndexService 构造⽅法");
}
@PostConstruct
public void init(){
System.out.println("IndexService init⽅法");
}
public void hello(){
System.out.println("IndexService hello");
}
}
测试类
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class);
//AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(IndexService.class);
IndexService indexService = (IndexService) Bean("indexService");
indexService.hello();
System.out.println(indexService);
}
第⼀⾏点进去
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//annotatedClasses ---> 配置类的class对象
this();
register(annotatedClasses);
refresh();
}
今天我们先看refresh()⽅法之前的源码
this()调的构造器如下
public AnnotationConfigApplicationContext() {
/**
* ⽗类的构造⽅法
* 创建⼀个读取注解的Bean定义读取器
* 什么是BeanDefinition
*/
super();
//可以⽤来扫描包或者类,继⽽转换成BeanDefinition
//但是实际上我们扫描包⼯作不是scanner这个对象来完成的
//是spring⾃⼰new的⼀个ClassPathBeanDefinitionScanner
//这⾥的scanner仅仅是为了程序员能够在外部调⽤AnnotationConfigApplicationContext对象的scan⽅法
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/**
* 这个类顾名思义是⼀个reader,⼀个读取器
* 读取什么呢?还是顾名思义:AnnotatedBeanDefinition意思是读取⼀个被加了注解的BeanDefinition
* 这个类在构造⽅法中实例化的
*/
private final AnnotatedBeanDefinitionReader reader;
/**
* 同意顾名思义,这是⼀个扫描器,扫描所有加了注解的bean
* 同样是在构造⽅法中被实例化的
*/
private final ClassPathBeanDefinitionScanner scanner;
先看super()⽗类构造器
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
可以看出初始化beanFactory 为默认实现DefaultListableBeanFactory
我们看⼀下些DefaultListableBeanFactory的属性和⽅法
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
//⼿动注册的单例对象的名称列表,按注册顺序排列
/
** List of names of manually registered singletons, in registration order. */
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
return getBean(requiredType, (Object[]) null);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(Class<T> requiredType, @ args) throws BeansException {
Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
if (resolved == null) {
throw new NoSuchBeanDefinitionException(requiredType);
}
return (T) resolved;
}
}
可以看出,这是bean⼯⼚的实现类,⾥⾯有存BeanDefinition和beanDefinitionNames 的map和getBean等⽅法
⽗类构造器结束,就是实例了⼀个默认的bean⼯⼚,继续下⼀⾏
点进去看源码
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
这⾥BeanDefinitionRegistry是⼀个BeanDefinition注册器
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
}
继续看最后⼀⾏
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
继续跟进去
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(DependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);//AnnotationAwareOrderComparator主要能解析@Order注解和@Priority
}
if (!(AutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());//ContextAnnotationAutowireCandidateResolver提供处理延迟加载的功能
}
}
//a Set of BeanDefinitionHolders, containing all bean definitions
//BeanDefinitionHolder是存储BeanDefinitionName和BeanDefinition的⼀个数据结构
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
//BeanDefinitio的注册,这⾥很重要,需要理解注册每个bean的类型,CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME=internalConfigurationAnnotationProcessor
if (!ainsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//ConfigurationClassPostProcessor是⼀个BeanFactory的后置处理器,主要功能是解析加了@Configuration的配置类,还会解析@ComponentScan、@ComponentScans注解扫描的包,以及解析@Import等注解 //需要注意的是ConfigurationClassPostProcessor的类型是BeanDefinitionRegistryPostProcessor
//⽽ BeanDefinitionRegistryPostProcessor 最终实现BeanFactoryPostProcessor这个接⼝
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME=internalAutowiredAnnotationProcessor
if (!ainsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//AutowiredAnnotationBeanPostProcessor是解析AutoWired注解的BeanPostProcessor
//AutowiredAnnotationBeanPostProcessor 实现了 MergedBeanDefinitionPostProcessor
//MergedBeanDefinitionPostProcessor 最终实现了 BeanPostProcessor
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//COMMON_ANNOTATION_PROCESSOR_BEAN_NAME=internalCommonAnnotationProcessor
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !ainsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//CommonAnnotationBeanPostProcessor⽀持对@PostConstruct和@PreDestroy注解,以及对@Resource注解的处理
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME=internalPersistenceAnnotationProcessor,跳过,不重要
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !ainsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
ClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); }
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); }
//EVENT_LISTENER_PROCESSOR_BEAN_NAME=internalEventListenerProcessor
if (!ainsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
//EventListenerMethodProcessor⽀持事件监听,不太熟
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
//EVENT_LISTENER_FACTORY_BEAN_NAME=internalEventListenerFactory
if (!ainsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
//DefaultEventListenerFactory不太了解,事件监听相关
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
这⾥的BeanDefinitionHolder看下
public class BeanDefinitionHolder implements BeanMetadataElement {
private final BeanDefinition beanDefinition;
private final String beanName;
@Nullable
private final String[] aliases;
//省略
}
可以认为:BeanDefinitionHolder是存储BeanDefinitionName和BeanDefinition的⼀个数据结构debug看下最后⼀⾏的结果
可以看出,bean⼯⼚已经存在5个BeanDefinition,我们继续看下⾯的源码
读取器看完了,扫描器先不看了,我们看register(annotatedClasses);⽅法
public void register(Class<?>... annotatedClasses) {
}
继续跟下去
public void register(Class<?>... annotatedClasses) {
for (Class<?> annotatedClass : annotatedClasses) {
registerBean(annotatedClass);
}
}
这⾥循环处理所有要处理的annotated类。如:Configuration注解的配置类
public void registerBean(Class<?> annotatedClass) {
doRegisterBean(annotatedClass, null, null, null);
}spring framework rce漏洞复现
继续跟
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, definitionCustomizers) { /**
* 根据指定的bean创建⼀个AnnotatedGenericBeanDefinition
* 这个AnnotatedGenericBeanDefinition可以理解为⼀个数据结构
* AnnotatedGenericBeanDefinition包含了类的其他信息,⽐如⼀些元信息
* scope,lazy等等.
* 此时因为传⼊的注解,所以new AnnotatedGenericBeanDefinition
*/
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
/**
* 判断这个类是否需要跳过解析
* 通过代码可以知道spring判断是否跳过解析,主要判断类有没有加注解
*/
if (ditionEvaluator.Metadata())) {
return;
}
abd.setInstanceSupplier(instanceSupplier);
/**
* 得到类的作⽤域 singleton
*/
ScopeMetadata scopeMetadata = solveScopeMetadata(abd);
/**
* 把类的作⽤域添加到数据结构结构中
*/
abd.ScopeName());
/**
* ⽣成类的名字通过beanNameGenerator
*/
String beanName = (name != null ? name : ateBeanName(abd, istry));
/**
* 处理类当中的通⽤注解
* 分析源码可以知道他主要处理
* Lazy DependsOn Primary Role等等注解
* 处理完成之后processCommonDefinitionAnnotations中依然是把他添加到AnnotatedGenericBeanDefinition数据结构当中 */
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {//qualifiers总是为null
for (Class<? extends Annotation> qualifier : qualifiers) {
//如果配置了@Primary注解,如果加了则作为⾸选
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
//懒加载注解
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
//如果使⽤了除@Primary和@Lazy以外的其他注解,则为该Bean添加⼀个根据名字⾃动装配的限定符
/
/这⾥难以理解,后⾯会详细介绍
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
//⾃定义注解
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
/**
* 这个BeanDefinitionHolder也是⼀个数据结构,这个对象放⼊了BeanDefinition和beanName
*/
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
/**
* ScopedProxyMode 这个知识点⽐较复杂,需要结合web去理解
* 可以暂时放⼀下,等说道springmvc的时候再说
* 或者看情况现在说也是⼀样的
*/
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, istry);
/**
* 把上述的这个数据结构注册给registry
* registy就是AnnotatonConfigApplicationContext
* AnnotatonConfigApplicationContext在初始化的時候通過調⽤⽗類的構造⽅法
* 實例化了⼀个DefaultListableBeanFactory
* *registerBeanDefinition⾥⾯就是把definitionHolder这个数据结构包含的信息注册到
* DefaultListableBeanFactory这个⼯⼚
*/
isterBeanDefinition(definitionHolder, istry);//关键代码
}
我们看最后⼀⾏关键代码
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
/
/ Register bean definition under primary name.
String beanName = BeanName();//获取beanName
//别名,先不看
// Register aliases for bean name, if any.
String[] aliases = Aliases();
if (aliases != null) {
for (String alias : aliases) {
}
}
}
还是跟关键代码
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
//DefaultListableBeanFactory
isterBeanDefinition(beanName, beanDefinition);
}
这⾥的beanFactory就是前⽂说的DefaultListableBeanFactory,继续跟
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
if (beanDefinition instanceof AbstractBeanDefinition) {//验证
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new ResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
//这⾥beanDefinitionMap是存储bean的name和.beanDefinition的map结果,此处有5个spring内置的BeanDefinition
BeanDefinition existingDefinition = (beanName);//这⾥的beanName是配置类的名字,existingDefinition应该为null if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (Role() < Role()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(existingDefinition)) {
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论