读Spring源码的一些杂乱思绪(二)

来源:互联网 发布:离坚白 知乎 编辑:程序博客网 时间:2024/06/06 07:51

下面写一些关于Annotation注解方面的东西。

<context:component-scan base-package="com.wtz.controller" />

这是我自己手打的一个spring扫包的自定义标签,这里的基本包扫描调用了ComponentScanBeanDefinitionParser的parse()方法,由于这是一个自定义标签,也是先拿到URI,然后去spring.handlers找到对应的Handler类,然后spring加载自定义标签的时候会load所有的配置文件,之后会调用到init方法,parse方法多态,会根据标签的不同来调用相应的解析器,如果不明白可以回去看一。
调用ComponentScanBeanDefinitionParser的parse()方法的过程中,做了三件重要的事情。
1.ConfigureScanner,配置扫描器。当我们在xml的bean中没有配置use-default-filters的时候,在spring的源码中其实已经默认帮我们配置成了boolean useDefaultFilters = true;在createScanner的时候注册了一个默认的过滤器。
ClassPathScanningCandidateComponentProvider类中

/**     * Register the default filter for {@link Component @Component}.     * <p>This will implicitly register all annotations that have the     * {@link Component @Component} meta-annotation including the     * {@link Repository @Repository}, {@link Service @Service}, and     * {@link Controller @Controller} stereotype annotations.     * <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and     * JSR-330's {@link javax.inject.Named} annotations, if available.     *     */    @SuppressWarnings("unchecked")    protected void registerDefaultFilters() {        this.includeFilters.add(new AnnotationTypeFilter(Component.class));        ClassLoader cl = ClassPathScanningCandidat eComponentProvider.class.getClassLoader();        try {            this.includeFilters.add(new AnnotationTypeFilter(                    ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));            logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");        }        catch (ClassNotFoundException ex) {            // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.        }        try {            this.includeFilters.add(new AnnotationTypeFilter(                    ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));            logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");        }        catch (ClassNotFoundException ex) {            // JSR-330 API not available - simply skip.        }    }

这里注册了默认的过滤器。可以看到添加了@Component,@ManagedBean,@”Named”,因为@Service,@Controller,@Repository是@Component的子注解,所以也算是被添加了进来。

2.scanner.doScan(basePackages);扫描器扫描基本包。其中有方法tokenizeToStringArray把.转换成/递归扫描到所有的文件,然后把文件封装成Resource对象。

/**     * Scan the class path for candidate components.     * @param basePackage the package to check for annotated classes     * @return a corresponding Set of autodetected bean definitions     */    public Set<BeanDefinition> findCandidateComponents(String basePackage) {        Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();        try {            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +                    resolveBasePackage(basePackage) + "/" + this.resourcePattern;            Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);            boolean traceEnabled = logger.isTraceEnabled();            boolean debugEnabled = logger.isDebugEnabled();            for (Resource resource : resources) {                if (traceEnabled) {                    logger.trace("Scanning " + resource);                }                if (resource.isReadable()) {                    try {                        MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);                        if (isCandidateComponent(metadataReader)) {                            ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);                            sbd.setResource(resource);                            sbd.setSource(resource);                            if (isCandidateComponent(sbd)) {                                if (debugEnabled) {                                    logger.debug("Identified candidate component class: " + resource);                                }                                candidates.add(sbd);                            }                            else {                                if (debugEnabled) {                                    logger.debug("Ignored because not a concrete top-level class: " + resource);                                }                            }                        }                        else {                            if (traceEnabled) {                                logger.trace("Ignored because not matching any filter: " + resource);                            }                        }                    }                    catch (Throwable ex) {                        throw new BeanDefinitionStoreException(                                "Failed to read candidate component class: " + resource, ex);                    }                }                else {                    if (traceEnabled) {                        logger.trace("Ignored because not readable: " + resource);                    }                }            }        }        catch (IOException ex) {            throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);        }        return candidates;    }

过滤掉有@Component,@Service,@Controller,@Repository注解的Resource,并把这些Resources封装成BeanDefinitions对象。

public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) {        processCommonDefinitionAnnotations(abd, abd.getMetadata());    }    static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {        if (metadata.isAnnotated(Lazy.class.getName())) {            abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value"));        }        else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) {            abd.setLazyInit(attributesFor(abd.getMetadata(), Lazy.class).getBoolean("value"));        }        if (metadata.isAnnotated(Primary.class.getName())) {            abd.setPrimary(true);        }        if (metadata.isAnnotated(DependsOn.class.getName())) {            abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value"));        }        if (abd instanceof AbstractBeanDefinition) {            AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;            if (metadata.isAnnotated(Role.class.getName())) {                absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue());            }            if (metadata.isAnnotated(Description.class.getName())) {                absBd.setDescription(attributesFor(metadata, Description.class).getString("value"));            }        }    }

在这个方法里把属性加上。

registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

这是我们注解处理类的入口

protected void registerComponents(            XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {        Object source = readerContext.extractSource(element);        CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);        for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {            compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));        }        // Register annotation config processors, if necessary.        boolean annotationConfig = true;        if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {            annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));        }        if (annotationConfig) {            Set<BeanDefinitionHolder> processorDefinitions =                    AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);            for (BeanDefinitionHolder processorDefinition : processorDefinitions) {                compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));            }        }        readerContext.fireComponentRegistered(compositeDef);    }

在这里把注解类注册进去才会起作用,比如下面这个方法

/**     * Register all relevant annotation post processors in the given registry.     * @param registry the registry to operate on     * @param source the configuration source element (already extracted)     * that this registration was triggered from. May be {@code null}.     * @return a Set of BeanDefinitionHolders, containing all bean definitions     * that have actually been registered by this call     */    public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(            BeanDefinitionRegistry registry, Object source) {        DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);        if (beanFactory != null) {            if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {                beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);            }            if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {                beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());            }        }        Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);        if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));        }        if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));        }        if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));        }        // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.        if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));        }        // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.        if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition();            try {                def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,                        AnnotationConfigUtils.class.getClassLoader()));            }            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));        }        if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));        }        if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {            RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);            def.setSource(source);            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));        }        return beanDefs;    }

3.ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor这些类是对@Autowired,@Required,@Resource的支持类,ioc依赖注入的时候需要调用这些类。

看PostProcessorRegistrationDelegate这个类里

public static void invokeBeanFactoryPostProcessors(            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {        // Invoke BeanDefinitionRegistryPostProcessors first, if any.        Set<String> processedBeans = new HashSet<String>();        if (beanFactory instanceof BeanDefinitionRegistry) {            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;            List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();            List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =                    new LinkedList<BeanDefinitionRegistryPostProcessor>();            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {                    BeanDefinitionRegistryPostProcessor registryPostProcessor =                            (BeanDefinitionRegistryPostProcessor) postProcessor;                    registryPostProcessor.postProcessBeanDefinitionRegistry(registry);                    registryPostProcessors.add(registryPostProcessor);                }                else {                    regularPostProcessors.add(postProcessor);                }            }            // Do not initialize FactoryBeans here: We need to leave all regular beans            // uninitialized to let the bean factory post-processors apply to them!            // Separate between BeanDefinitionRegistryPostProcessors that implement            // PriorityOrdered, Ordered, and the rest.            String[] postProcessorNames =                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.            List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();            for (String ppName : postProcessorNames) {                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {                    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));                    processedBeans.add(ppName);                }            }            sortPostProcessors(beanFactory, priorityOrderedPostProcessors);            registryPostProcessors.addAll(priorityOrderedPostProcessors);            invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);            List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();            for (String ppName : postProcessorNames) {                if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {                    orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));                    processedBeans.add(ppName);                }            }            sortPostProcessors(beanFactory, orderedPostProcessors);            registryPostProcessors.addAll(orderedPostProcessors);            invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.            boolean reiterate = true;            while (reiterate) {                reiterate = false;                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);                for (String ppName : postProcessorNames) {                    if (!processedBeans.contains(ppName)) {                        BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);                        registryPostProcessors.add(pp);                        processedBeans.add(ppName);                        pp.postProcessBeanDefinitionRegistry(registry);                        reiterate = true;                    }                }            }            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.            invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);        }        else {            // Invoke factory processors registered with the context instance.            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);        }        // Do not initialize FactoryBeans here: We need to leave all regular beans        // uninitialized to let the bean factory post-processors apply to them!        String[] postProcessorNames =                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,        // Ordered, and the rest.        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();        List<String> orderedPostProcessorNames = new ArrayList<String>();        List<String> nonOrderedPostProcessorNames = new ArrayList<String>();        for (String ppName : postProcessorNames) {            if (processedBeans.contains(ppName)) {                // skip - already processed in first phase above            }            else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));            }            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {                orderedPostProcessorNames.add(ppName);            }            else {                nonOrderedPostProcessorNames.add(ppName);            }        }        // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.        sortPostProcessors(beanFactory, priorityOrderedPostProcessors);        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);        // Next, invoke the BeanFactoryPostProcessors that implement Ordered.        List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();        for (String postProcessorName : orderedPostProcessorNames) {            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));        }        sortPostProcessors(beanFactory, orderedPostProcessors);        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);        // Finally, invoke all other BeanFactoryPostProcessors.        List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();        for (String postProcessorName : nonOrderedPostProcessorNames) {            nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));        }        invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);        // Clear cached merged bean definitions since the post-processors might have        // modified the original metadata, e.g. replacing placeholders in values...        beanFactory.clearMetadataCache();    }

其中BeanDefinitionRegistryPostProcessor这个接口很重要。

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package org.springframework.beans.factory.support;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanFactoryPostProcessor;public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry var1) throws BeansException;}

这个接口继承自BeanFactoryPostProcessor。实现该接口可以实现对bean的修改。

下面举一个利用该接口修改Bean的例子:
首先定义一个类Student

package com.modifybean;public class Student {    public String username;    public String password;    public String school;    public String getSchool() {        return school;    }    public void setSchool(String school) {        this.school = school;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}

在XML文件中把

<bean id="student" class="com.modifybean.Student">        <property name="username" value="xiaoming"></property>        <property name="password" value="123456"></property></bean>

这个bean加进去,在StudentTest中获取这个bean

package com.modifybean;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.BeansException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Created by wtz on 2017/9/19. */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})public class StudentTest implements ApplicationContextAware{    @Autowired    public  ApplicationContext applicationContext;    @Test    public void testStudent(){        Student student = (Student) applicationContext.getBean("student");        System.out.println("username =" + student.getUsername() + " ,password =" + student.getPassword() + " ,school =" + student.getSchool());    }    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }}

这里写图片描述
可以看到我们获取到了bean。

username =xiaoming ,password =123456 ,school =null

新建类MyChange1

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.MutablePropertyValues;import org.springframework.beans.factory.config.BeanDefinition;import org.springframework.beans.factory.config.BeanFactoryPostProcessor;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;public class MyChange1 implements BeanFactoryPostProcessor {    @Override    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        System.out.println("BeanFactoryPostProcessor MyChange1");        BeanDefinition bd = arg0.getBeanDefinition("student");        MutablePropertyValues mpv = bd.getPropertyValues();        mpv.addPropertyValue("password", "woshimima1");    }}

MyChange2

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.MutablePropertyValues;import org.springframework.beans.factory.config.BeanDefinition;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;public class MyChange2 implements BeanDefinitionRegistryPostProcessor {    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        // TODO Auto-generated method stub    }    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0)            throws BeansException {        System.out.println("BeanDefinitionRegistryPostProcessor MyChange2");        BeanDefinition bd = arg0.getBeanDefinition("student");        MutablePropertyValues mpv = bd.getPropertyValues();        mpv.addPropertyValue("username", "woshiname1");    }}

MyChange3

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;import org.springframework.core.PriorityOrdered;public class MyChange3 implements BeanDefinitionRegistryPostProcessor,PriorityOrdered {    @Override    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        // TODO Auto-generated method stub    }    @Override    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0)            throws BeansException {        System.out.println("BeanDefinitionRegistryPostProcessor PriorityOrdered MyChange3");    }    @Override    public int getOrder() {        // TODO Auto-generated method stub        return 0;    }}

MyChange4

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;import org.springframework.core.PriorityOrdered;public class MyChange4 implements BeanDefinitionRegistryPostProcessor,        PriorityOrdered {    @Override    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        // TODO Auto-generated method stub    }    @Override    public int getOrder() {        // TODO Auto-generated method stub        return 1;    }    @Override    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0)            throws BeansException {        System.out.println("BeanDefinitionRegistryPostProcessor PriorityOrdered MyChange4");    }}

MyChange5

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.MutablePropertyValues;import org.springframework.beans.factory.config.BeanDefinition;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;import org.springframework.core.Ordered;public class MyChange5 implements BeanDefinitionRegistryPostProcessor, Ordered {    @Override    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        // TODO Auto-generated method stub    }    @Override    public int getOrder() {        // TODO Auto-generated method stub        return 0;    }    @Override    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0)            throws BeansException {        System.out.println("BeanDefinitionRegistryPostProcessor Ordered MyChange5");        BeanDefinition bd = arg0.getBeanDefinition("student");        MutablePropertyValues mpv = bd.getPropertyValues();        mpv.addPropertyValue("school", "wtzschool");    }}

MyChange6

package com.modifybean;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.support.BeanDefinitionRegistry;import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;import org.springframework.core.Ordered;public class MyChange6 implements BeanDefinitionRegistryPostProcessor, Ordered {    @Override    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)            throws BeansException {        // TODO Auto-generated method stub    }    @Override    public int getOrder() {        // TODO Auto-generated method stub        return 1;    }    @Override    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry arg0)            throws BeansException {        System.out.println("BeanDefinitionRegistryPostProcessor Ordered MyChange6");    }}

在xml文件中添加

<bean id="myChange1" class="com.modifybean.MyChange1"></bean>    <bean id="myChange2" class="com.modifybean.MyChange2"></bean>    <bean id="myChange3" class="com.modifybean.MyChange3"></bean>    <bean id="myChange4" class="com.modifybean.MyChange4"></bean>    <bean id="myChange5" class="com.modifybean.MyChange5"></bean>    <bean id="myChange6" class="com.modifybean.MyChange6"></bean>

此时运行我们可以看到Log
这里写图片描述
student被改变为

username =woshiname1 ,password =woshimima1 ,school =wtzschool

这里写图片描述

同时implements BeanDefinitionRegistryPostProcessor,PriorityOrdered,并且

@Override    public int getOrder() {        // TODO Auto-generated method stub        return 0;    }

getOrder值最小优先级最高。

之后是implements BeanDefinitionRegistryPostProcessor,PriorityOrdered,getOrder值最小优先级最高。

再之后是implements BeanDefinitionRegistryPostProcessor。

最后才是implements BeanFactoryPostProcessor。

以上就是我对Spring源码中Annotation的一些理解。

原创粉丝点击