Spring中常用扩展点以及执行顺序

Spring中让人眼前一亮的11个小技巧 我们一说到spring,可能第一个想到的是IOC(控制反转) 和AOP(面向切面编程)。没错,它们是spring的基石,得益于它们的优秀设计,使得spring能够从众多优秀框架中脱颖而出。除此之外,我们在使用spring的过程中,有没有发现它的扩展能力非常强。由于这个优势的存在,让spring拥有强大的包容能力,让很多第三方应用能够轻松投入spring的怀抱。比如:rocketmq、mybatis、redis等。今天跟大家一起聊聊,在Spring中最常用的11个扩展点。 阅读详情

1、Spring中常用的扩展点

  • org.springframework.boot.env.EnvironmentPostProcessor

  • org.springframework.context.ApplicationContextInitializer

  • org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor

  • org.springframework.beans.factory.config.BeanFactoryPostProcessor

  • org.springframework.beans.factory.BeanNameAware

  • org.springframework.context.EnvironmentAware

  • org.springframework.context.ApplicationContextAware

  • org.springframework.beans.factory.InitializingBean

  • javax.annotation.PostConstruct

  • org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor

  • org.springframework.beans.factory.config.BeanPostProcessor

  • org.springframework.boot.ApplicationRunner

  • org.springframework.boot.CommandLineRunner

Spring中很非常多的扩展点,用户可以根据自己的项目按需扩展自己的方法,然后统一被Springboot管理。每一个扩展点执行的时机和作用都是不一样的。笔者这里总结了自己常用的一些扩展点。

2、EnvironmentPostProcessor

org.springframework.boot.env.EnvironmentPostProcessor

/**
 * Allows for customization of the application's {@link Environment} prior to the
 * application context being refreshed.
 * <p>
 * EnvironmentPostProcessor implementations have to be registered in
 * {@code META-INF/spring.factories}, using the fully qualified name of this class as the
 * key. Implementations may implement the {@link org.springframework.core.Ordered Ordered}
 * interface or use an {@link org.springframework.core.annotation.Order @Order} annotation
 * if they wish to be invoked in specific order.
 * <p>
 * Since Spring Boot 2.4, {@code EnvironmentPostProcessor} implementations may optionally
 * take the following constructor parameters:
 * <ul>
 * <li>{@link DeferredLogFactory} - A factory that can be used to create loggers with
 * output deferred until the application has been fully prepared (allowing the environment
 * itself to configure logging levels).</li>
 * <li>{@link Log} - A log with output deferred until the application has been fully
 * prepared (allowing the environment itself to configure logging levels).</li>
 * <li>{@link ConfigurableBootstrapContext} - A bootstrap context that can be used to
 * store objects that may be expensive to create, or need to be shared
 * ({@link BootstrapContext} or {@link BootstrapRegistry} may also be used).</li>
 * </ul>
 *
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @since 1.3.0
 */
@FunctionalInterface
public interface EnvironmentPostProcessor {

    /**
     * Post-process the given {@code environment}.
     * @param environment the environment to post-process
     * @param application the application to which the environment belongs
     */
    void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);

}

该扩展点可以获取上下文的环境以及上下文。SpringApplication 增加一些ApplicationContextInitializer 等参数。也是项目启动时,整理的扩展点中最先执行的扩展点。

注释钟也说明了,该扩展的的配置必须配置在META-INF/spring.factories 中。如:org.springframework.boot.env.EnvironmentPostProcessor=xxx.MyEnvironmentPostProcessor

Spring 官网中也给了答案:

https://docs.spring.io/spring-boot/docs/2.5.2/reference/htmlsingle/#howto.application.customize-the-environment-or-application-context

3、ApplicationContextInitializer

org.springframework.context.ApplicationContextInitializer

/**
 * Callback interface for initializing a Spring {@link ConfigurableApplicationContext}
 * prior to being {@linkplain ConfigurableApplicationContext#refresh() refreshed}.
 *
 * <p>Typically used within web applications that require some programmatic initialization
 * of the application context. For example, registering property sources or activating
 * profiles against the {@linkplain ConfigurableApplicationContext#getEnvironment()
 * context's environment}. See {@code ContextLoader} and {@code FrameworkServlet} support
 * for declaring a "contextInitializerClasses" context-param and init-param, respectively.
 *
 * <p>{@code ApplicationContextInitializer} processors are encouraged to detect
 * whether Spring's {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented or if the {@link org.springframework.core.annotation.Order @Order}
 * annotation is present and to sort instances accordingly if so prior to invocation.
 *
 * @author Chris Beams
 * @since 3.1
 * @param <C> the application context type
 * @see org.springframework.web.context.ContextLoader#customizeContext
 * @see org.springframework.web.context.ContextLoader#CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see org.springframework.web.servlet.FrameworkServlet#setContextInitializerClasses
 * @see org.springframework.web.servlet.FrameworkServlet#applyInitializers
 */
@FunctionalInterface
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

    /**
     * Initialize the given application context.
     * @param applicationContext the application to configure
     */
    void initialize(C applicationContext);

}

初始化上下文后的一个回调,可以直接拿到上下文。通过上下文可以获取到上文的环境getEnvironment() 。

执行的时机实在上下初始化之后,实例化Bean之前执行的。

使用场景:初始化上下文之后,对Bean属性的检查可以放在这里处理,例如IP、url是否可用等

配置:ApplicationContextInitializer 配置有三种方式

  • 方式一:扩展类配置

    /**
     *
     * https://docs.spring.io/spring-boot/docs/2.5.2/reference/htmlsingle/#howto.application.customize-the-environment-or-application-context
     *
     * @author: ws
     * @date: 2025/1/16 15:07
     */
    public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
    
        @Override
        public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
            application.addInitializers(new MyApplicationContextInitializer());
            System.out.println(">>>>>>>>>>>>>>>>MyEnvironmentPostProcessor -------------------------->");
        }
    }
    
  • 方式二:Java启动类增加参数

    @SpringBootApplication
    public class SpringbootExtendApplication {
    
        public static void main(String[] args) {
            //SpringApplication.run(SpringbootExtendApplication.class, args);
            SpringApplication application = new SpringApplication(SpringbootExtendApplication.class);
            application.addInitializers(new MyApplicationContextInitializer());
            application.run(args);
        }
    
    }
    
  • 方式三:在配置文件中配置

    context.initializer.classes=xx.xx.MyApplicationContextInitializer
    
  • 方式四: 在META-INF/spring.factories 【推荐】

    org.springframework.context.ApplicationContextInitializer=xx.xx.MyApplicationContextInitializer
    
    
    

4、BeanDefinitionRegistryPostProcessor

org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor

/**
 * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
 * the registration of further bean definitions <i>before</i> regular
 * BeanFactoryPostProcessor detection kicks in. In particular,
 * BeanDefinitionRegistryPostProcessor may register further bean definitions
 * which in turn define BeanFactoryPostProcessor instances.
 *
 * @author Juergen Hoeller
 * @since 3.0.1
 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor
 */
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean definition registry after its
     * standard initialization. All regular bean definitions will have been loaded,
     * but no beans will have been instantiated yet. This allows for adding further
     * bean definitions before the next post-processing phase kicks in.
     * @param registry the bean definition registry used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

从源码中可以看出BeanDefinitionRegistryPostProcessor 继承 BeanFactoryPostProcessor ,也就是 BeanDefinitionRegistryPostProcessor 拥有更丰富的功能。

该扩展可以通过BeanDefinitionRegistry获取BeanDefinition ,然后根据需要修改或者其他处理。 同时还具备BeanFactoryPostProcessor 扩展的功能。

5、BeanFactoryPostProcessor

org.springframework.beans.factory.config.BeanFactoryPostProcessor

@FunctionalInterface
public interface BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean factory after its standard
     * initialization. All bean definitions will have been loaded, but no beans
     * will have been instantiated yet. This allows for overriding or adding
     * properties even to eager-initializing beans.
     * @param beanFactory the bean factory used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

可以通过方法获取ConfigurableListableBeanFactory ,可以用来获取任意的Bean等操作

6、BeanNameAware | EnvironmentAware | ApplicationContextAware

  • org.springframework.beans.factory.BeanNameAware

这三个扩展点比较简单就是对外提供BeanName、Environment和ApplicationContext

public interface BeanNameAware extends Aware {

    /**
     * Set the name of the bean in the bean factory that created this bean.
     * <p>Invoked after population of normal bean properties but before an
     * init callback such as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method.
     * @param name the name of the bean in the factory.
     * Note that this name is the actual bean name used in the factory, which may
     * differ from the originally specified name: in particular for inner bean
     * names, the actual bean name might have been made unique through appending
     * "#..." suffixes. Use the {@link BeanFactoryUtils#originalBeanName(String)}
     * method to extract the original bean name (without suffix), if desired.
     */
    void setBeanName(String name);

}
  • org.springframework.context.EnvironmentAware
/**
 * Interface to be implemented by any bean that wishes to be notified
 * of the {@link Environment} that it runs in.
 *
 * @author Chris Beams
 * @since 3.1
 * @see org.springframework.core.env.EnvironmentCapable
 */
public interface EnvironmentAware extends Aware {

    /**
     * Set the {@code Environment} that this component runs in.
     */
    void setEnvironment(Environment environment);

}
  • org.springframework.context.ApplicationContextAware
public interface ApplicationContextAware extends Aware {

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException if thrown by application context methods
     * @see org.springframework.beans.factory.BeanInitializationException
     */
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

初始化容器之后依次执行。

7、InitializingBean | PostConstruct

org.springframework.beans.factory.InitializingBean

public interface InitializingBean {

    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     * @throws Exception in the event of misconfiguration (such as failure to set an
     * essential property) or if initialization fails for any other reason
     */
    void afterPropertiesSet() throws Exception;

}

javax.annotation.PostConstruct

这是一个注解和InitializingBean 实现的目标是一样的,都是在Bean实例化之后调用。

这里的执行顺序InitializingBean 是优先注解执行的。

8、InstantiationAwareBeanPostProcessor

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {


    @Nullable
    default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }


    default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }


    @Nullable
    default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
            throws BeansException {

        return null;
    }
}

InstantiationAwareBeanPostProcessor 是Bean实例化的后置处理器,也就是分别在Bean实例化前执行postProcessBeforeInstantiation() ,实例化之后执行postProcessAfterInstantiation(), 还增加了PropertyValues 的扩展。

由于InstantiationAwareBeanPostProcessor 继承BeanPostProcessor ,所以还具备BeanPostProcessor 初始化的前后的功能。

9、BeanPostProcessor

org.springframework.beans.factory.config.BeanPostProcessor

public interface BeanPostProcessor {

    /**
     * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>The default implementation returns the given {@code bean} as-is.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     * if {@code null}, no subsequent BeanPostProcessors will be invoked
     * @throws org.springframework.beans.BeansException in case of errors
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
     */
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
     * instance and the objects created by the FactoryBean (as of Spring 2.0). The
     * post-processor can decide whether to apply to either the FactoryBean or created
     * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
     * <p>This callback will also be invoked after a short-circuiting triggered by a
     * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
     * in contrast to all other {@code BeanPostProcessor} callbacks.
     * <p>The default implementation returns the given {@code bean} as-is.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     * if {@code null}, no subsequent BeanPostProcessors will be invoked
     * @throws org.springframework.beans.BeansException in case of errors
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
     * @see org.springframework.beans.factory.FactoryBean
     */
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}

就是在Bean初始化前后执行的处理器。

实例化:实例化就是创建空对象,对象的属性还没有填充

初始化:实例化之后的对象,需要填充对象、赋默认值等操作。

注意点:由于BeanPostProcessor 在BeanFactory生命周期内被Bean调用。如果通过BeanDefinitionRegistryPostProcessor 或其他 beanFactory.getBean(“XX”)的方式提前完成Bean的实例化,Bean就是在注册BeanPostProcessor 之前执行。定义的BeanPostProcessor 扩展点就无法“XX”的后置处理器(检测不到XX这个Bean)。

A a = (A)configurableListableBeanFactory.getBean("a");
a.test2();

10、ApplicationRunner | CommandLineRunner

  • org.springframework.boot.ApplicationRunner
/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link ApplicationRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 *
 * @author Phillip Webb
 * @since 1.3.0
 * @see CommandLineRunner
 */
@FunctionalInterface
public interface ApplicationRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming application arguments
     * @throws Exception on error
     */
    void run(ApplicationArguments args) throws Exception;

}
  • org.springframework.boot.CommandLineRunner
/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 * <p>
 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @since 1.0.0
 * @see ApplicationRunner
 */
@FunctionalInterface
public interface CommandLineRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    void run(String... args) throws Exception;

}

ApplicationRunner 和 CommandLineRunner 都是在项目启动完成之后执行的扩展点,但是ApplicationRunner 优先于CommandLineRunner 执行,两者处理参数的方式稍有不同。

spring之扩展点 spring 扩展点的介绍和使用示例,模拟简单实现AOP管理事务。 阅读详情

相关推荐

ESP32S3学习——i2c,点亮0.96寸oled

ESP32S3学习——i2c,点亮0.96寸oled

HandBAI的博客 1万+

【Spring源码】Spring扩展点及顺序

BeanFactoryPostProcessor的构造器JBeanFactoryPostProcessor的postProcessBeanFactory了BeanPostProcessor构造器 InstantiationAwareBeanPostProcessor构造方法了InstantiationAwareBeanPostProcessor接口的BeforeInstantiationxqBean]无参构造器调用 JInstantiationAwareBeanPostProcessor接口的AfterIn

wenchun001的博客 642

用angr找到strcpy的栈溢出漏洞

这篇文章其实是分析angr文档里给出的一个挖漏洞的小例子。 原文链接在此:https://docs.angr.io/examples#beginner-vulnerability-discovery-example-strcpy_find 这是第一个用angr在二进制里找可利用条件的教程。第一个例子是一个非常简单的程序。这个angr脚本会从程序的entry到strcpy找到一条路径。(只有我们能够控制strcpy的参数的时候) 为了找到正确的路径,angr需要去算一个密码参数,算这个密码,angr只要2s

^_^ 1221

全网最全 spring常用拓展点调用顺序 说明总结图

spring在bean的整个生命周期中留了很多拓展点以供使用者能够获取上下文信息,或者在bean生命周期中的某个节点对bean进行调整,了解这些拓展点,能够更好地了解bean的生命周期

qq_40094078的博客 745

若依框架整合Flowable:从零构建企业级流程中心

本文详细介绍了如何将若依框架与Flowable工作流引擎整合,构建企业级流程中心。通过环境配置、依赖添加、数据库设置等核心步骤,实现流程定义管理、任务处理服务等关键功能,并结合实际案例展示请假审批流程的实现与动态表单集成。文章还提供了性能优化和生产建议,帮助开发者高效构建稳定可靠的工作流系统。

weixin_28365523的博客 230

arcgis导出自身相交数据

今天接到一个客户需求,一份面文件,里面有好多元素是两两相交甚至是三个相交的,现在要把这些重叠部分提取出来,并且把相交部分的原始要素的名称也保留在字段中,也就是说名称这个会有好多个名称字段,如果两个要素相交那就是前两个名称字段有值,后面的为空,如果是三个要素相交,那么输出的这个要素就是前三个名称字段有值,后面的为空,嗯,这里也不太确定会出现多少个名称字段,这个需要依照数据来定。 这是原始数据,...

miaowumi92的博客 6790

spring中的扩展点解析以及实践使用

这是整个spring容器在刷新之前初始化`ConfigurableApplicationContext`的回调接口,简单来说,就是在容器刷新之前调用此类的`initialize`方法。这个点允许被用户自己扩展。用户可以在整个spring容器还没被初始化之前做一些事情。

itboy 1543

从零开始:如何用Kimi OK Computer快速生成专业级数据分析报告和PPT(附实战案例)

本文详细介绍了如何利用Kimi OK Computer智能体模式,从零开始快速生成专业级数据分析报告和演示文稿。通过实战案例,解析了其任务规划、联网搜索、多工具协同和内容排版等核心能力,并提供了精准指令构造、工作流引导及成果精修的完整步骤,帮助用户高效完成从数据到成品的端到端交付。

weixin_29284201的博客 372

spring--扩展点

扩展点: BeanFactoryPostProcessor 构建 BeanFactory后调用,此时BeanFactory , BeanDefinition 已经解析完毕。 BeanPostProcessor 初始化 Bean 对象时调用,所有bean的构建都会调用这个接口的两个方法。两个方法参数传入的bean属性都已经注入完毕。 InitializingBean Bean 实例创建后,所有的属性...

convict_EVA的专栏 1934

Unity2D像素刀光实现:粒子方向控制与像素级渲染规范

像素风游戏中的刀光特效并非普通粒子动画,而是需严格遵循像素艺术原理的视觉暂留模拟。其核心在于将‘瞬时切割感’转化为程序可执行的渲染逻辑:通过禁用纹理滤波保障1:1像素锐度,绑定刀锋向量控制粒子运动方向,限定≤0.15秒生命周期匹配人眼暂留阈值,并采用Stretched Billboard实现动态拉伸拖影。该方案兼顾美术语义(如直劈、横扫、突刺)与工程约束(Sorting Layer分层、对象池复用、单粒子GPU优化),广泛适用于Unity2D平台的动作反馈系统,尤其适配《空洞骑士》《死亡细胞》类高节奏像素R

weixin_32390647的博客 288

Spring Boot的启动流程,以及各个扩展点的执行顺序

摘要: 本文详细解析了SpringBoot应用中容器初始化及组件的执行顺序:1)Bean构造方法最先执行;2)依赖注入完成后触发@PostConstruct方法;3)InitializingBean接口的afterPropertiesSet()方法;4)@Bean自定义初始化方法。随后,ContextRefreshedEvent监听器响应上下文就绪事件,ApplicationRunner和CommandLineRunner最后执行。通过@Order、@DependsOn或Ordered接口可控制执行顺序。理

ddu-to-end的博客 2323

基于STM32单片机的环境监测系统设计与实现

综上所述,基于STM32单片机的环境监测系统具有良好的实时性、准确性和稳定性,能够满足环境监测的需求。本系统的研究意义在于,首先,它能够为用户提供准确的室内空气质量信息,帮助用户了解室内环境的质量状况,从而采取相应的措施来改善室内环境。本文设计并实现了一种基于STM32单片机的环境监测系统,该系统能够实时监测并显示室内环境的温湿度、甲醛浓度以及二氧化碳浓度,为用户提供准确的空气质量信息。实验过程中,我们模拟了不同的环境条件,包括温湿度变化、甲醛和二氧化碳浓度的波动等,以测试系统的实时性、准确性和稳定性。

3254968421的博客 2万+

Spring常用扩展点

一、BeanPostProcessor 如果你想在Spring容器完成实例化,配置和初始化bean之后实现一些自定义逻辑,则可以插入一个或多个自定义BeanPostProcessor实现。这些实现成为后置处理器。 BeanPostProcessor接口包含两个回调方法。 当实现此接口类通过容器注册为后处理器时,由Spring容器实例的Bean,Spring容器会在bean 的init方法执行前回调postProcessBeforeInitialization方法, 然后会在bean初始化之后回

Jak的博客 1万+

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring 中的扩展点

Spring框架中的BeanDefinitionRegistryPostProcessor、BeanFactoryPostProcessor和BeanPostProcessor是三个核心扩展点,分别在容器启动的不同阶段发挥作用。BeanDefinitionRegistryPostProcessor(继承自BeanFactoryPostProcessor)允许动态注册Bean定义,优先于其他处理器执行;BeanFactoryPostProcessor在Bean定义注册完成后、实例化前修改配置;BeanPost

红血哥 1254

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

spring的扩展点总结

zzzz

ww0peo的博客 1366

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

万字长文带你窥探Spring中所有的扩展点

Spring的核心思想就是容器,当容器refresh的时候,外部看上去风平浪静,其实内部则是一片惊涛骇浪,汪洋一片。Springboot更是封装了Spring,遵循约定大于配置,加上自动装配的机制。很多时候我们只要引用了一个依赖,几乎是零配置就能完成一个功能的装配。由spring提供的、在容器或bean生命周期各个阶段、供spring框架回调使用的函数方法,即为扩展点。扩展点体现了Spring框架的灵活性、业务亲和性。

SevenCoding的博客 3382

Spring扩展点系列-ApplicationContextAwareProcessor

今天要介绍的是ApplicationContextAwareProcessor ,ApplicationContextAwareProcessor 本身是没有扩展点的,但其内部却有7个扩展点可供实现 ,分别为这些内部扩展点触发的时机在bean实例化之后,初始化之前。

qq_32590535的博客 1554

窥探Spring中所有的扩展点

这是整个spring容器在刷新之前初始化的回调接口,简单来说,就是在容器刷新refresh之前调用此类的initialize方法。这个接口的主要目的是在 Spring 应用上下文初始化的早期阶段进行一些配置或调整,以便在上下文加载后可以使用这些配置。此接口,自己没有提供任何的实现类,但在SpringBoot对它有较多的扩展实现。这个接口是的扩展接口,调用时机在spring在读取信息之后,实例化bean之前。

lkf19711的博客 872

spring中的扩展点你都知道吗(涵盖几乎所有扩展点-及其使用方法)

Spring MVC拦截器,它可以获得HttpServletRequest和HttpServletResponse等web对象实例。preHandle 在目标方法执行之前执行执行目标方法后执行的postHandleafterCompletion 在请求完成时执行为了方便,我们一般继承HandlerInterceptorAdapter,它实现了HandlerInterceptor。如果有授权鉴权、日志、统计等场景,可以使用该拦截器,我们来演示下吧。

奇点 1701

Spring组件实例化扩展点:InstantiationAwareBeanPostProcessor

是 Spring 生命周期中的一个关键扩展接口,继承自。它在 Bean 的实例化阶段拦截 Bean 的实例化过程,甚至完全自定义实例化逻辑在属性填充(依赖注入)前后执行自定义操作动态修改 Bean 的定义或属性值,实现更灵活的控制与普通的不同,该接口的关注点集中在 Bean 的实例化阶段,而非初始化阶段(如或为 Spring Bean 的生命周期提供了深度的扩展能力,尤其在实例化阶段和属性注入阶段。通过合理利用其回调方法,开发者可以实现高度定制化的 Bean 管理逻辑,如动态代理、属性加密、依赖注入扩展等。

从基础到源码解析的学习记录 4138

Spring容器扩展点

Spring容器扩展带点

zhujilisa的博客 843

【Spring源码分析】4、Spring Bean 生命周期扩展点 PostProcessor 和 Aware 分析

1、Spring Bean 生命周期扩展点 spring bean的整个生命周期中穿插了各种各样的组件,工具等信息,spring在各个阶段也为我们提供了各式各样的扩展点,其中最核心的分为两大类,PostProcessor接口的实现类和Aware接口的实现类 (1)PostProcessor接口类 PostProcessor接口常用类分为两种,一种是BeanPostProcessor,另一种是BeanFactoryPostProcessor,我这里只是举例说明常用的类有哪些,实际上实现类是非常多的,其中相关常

Tellsea 2168

Spring的一些常见扩展点

整理一些spring常用的扩展点,相同章节的方法按执行顺序排列。 持续更新中… 1 spring-beans常见扩展点 1.1 Bean实例化[getBean()] InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(): 实例化前调用,可以在这里修改BeanDefinition。如果这里返回不为空,会直接略过后续的bean创建过程,将返回结果当作此次创建的bean。[代码位置:createBean/resolveBefore

ppprog的博客 2479

【Spring】扩展点(三):BeanPostProcessor、InstantiationAwareBeanPostProcessor、BeanFactoryPostProcessor

前言:【Spring】扩展点(一):InitialingBean、DisposableBean、BeanPostProcessor、InstantiationAwareBeanPostProcessor 1.FactoryBean 传统的 Spring 容器加载一个 bean 的整个过程,都是由 Spring 控制的,换句话说,开发者除了设置Bean相关属性之外,是没有太多的自主权的。FactoryBean 改变了这一点,开发者可以个性化地定制自己想要实例化出来的 Bean,方法就是实现 Factory.

A minor 4114
上一篇: 数据库同步工具-Bifrost
下一篇: Springboot使用war启动的配置
智_永无止境
博客等级 码龄10年 803粉丝 407原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智_永无止境

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值