Java后台框架篇--Spring中Bean的生命周期

Spring Bean的生命周期 Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。 阅读详情

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。

 转载请注明地址 http://www.cnblogs.com/zrtqsk/p/3735273.html,谢谢。

一、生命周期流程图:

  Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。

 

若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

 

二、各种接口方法分类

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

1、Bean自身的方法  :  这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法

2、Bean级生命周期接口方法  :  这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法

3、容器级生命周期接口方法  :  这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

4、工厂后处理器接口方法  :  这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器  接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

  

三、演示

我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。

1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:

 

复制代码
 1 package springBeanTest;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.BeanFactory;
 5 import org.springframework.beans.factory.BeanFactoryAware;
 6 import org.springframework.beans.factory.BeanNameAware;
 7 import org.springframework.beans.factory.DisposableBean;
 8 import org.springframework.beans.factory.InitializingBean;
 9 
10 /**
11  * @author qsk
12  */
13 public class Person implements BeanFactoryAware, BeanNameAware,
14         InitializingBean, DisposableBean {
15 
16     private String name;
17     private String address;
18     private int phone;
19 
20     private BeanFactory beanFactory;
21     private String beanName;
22 
23     public Person() {
24         System.out.println("【构造器】调用Person的构造器实例化");
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         System.out.println("【注入属性】注入属性name");
33         this.name = name;
34     }
35 
36     public String getAddress() {
37         return address;
38     }
39 
40     public void setAddress(String address) {
41         System.out.println("【注入属性】注入属性address");
42         this.address = address;
43     }
44 
45     public int getPhone() {
46         return phone;
47     }
48 
49     public void setPhone(int phone) {
50         System.out.println("【注入属性】注入属性phone");
51         this.phone = phone;
52     }
53 
54     @Override
55     public String toString() {
56         return "Person [address=" + address + ", name=" + name + ", phone="
57                 + phone + "]";
58     }
59 
60     // 这是BeanFactoryAware接口方法
61     @Override
62     public void setBeanFactory(BeanFactory arg0) throws BeansException {
63         System.out
64                 .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
65         this.beanFactory = arg0;
66     }
67 
68     // 这是BeanNameAware接口方法
69     @Override
70     public void setBeanName(String arg0) {
71         System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
72         this.beanName = arg0;
73     }
74 
75     // 这是InitializingBean接口方法
76     @Override
77     public void afterPropertiesSet() throws Exception {
78         System.out
79                 .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
80     }
81 
82     // 这是DiposibleBean接口方法
83     @Override
84     public void destroy() throws Exception {
85         System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
86     }
87 
88     // 通过<bean>的init-method属性指定的初始化方法
89     public void myInit() {
90         System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
91     }
92 
93     // 通过<bean>的destroy-method属性指定的初始化方法
94     public void myDestory() {
95         System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
96     }
97 }
复制代码

 

2、接下来是演示BeanPostProcessor接口的方法,如下:

复制代码
 1 package springBeanTest;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.config.BeanPostProcessor;
 5 
 6 public class MyBeanPostProcessor implements BeanPostProcessor {
 7 
 8     public MyBeanPostProcessor() {
 9         super();
10         System.out.println("这是BeanPostProcessor实现类构造器!!");
11         // TODO Auto-generated constructor stub
12     }
13 
14     @Override
15     public Object postProcessAfterInitialization(Object arg0, String arg1)
16             throws BeansException {
17         System.out
18         .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
19         return arg0;
20     }
21 
22     @Override
23     public Object postProcessBeforeInitialization(Object arg0, String arg1)
24             throws BeansException {
25         System.out
26         .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
27         return arg0;
28     }
29 }
复制代码

如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。

 

3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:

复制代码
 1 package springBeanTest;
 2 
 3 import java.beans.PropertyDescriptor;
 4 
 5 import org.springframework.beans.BeansException;
 6 import org.springframework.beans.PropertyValues;
 7 import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
 8 
 9 public class MyInstantiationAwareBeanPostProcessor extends
10         InstantiationAwareBeanPostProcessorAdapter {
11 
12     public MyInstantiationAwareBeanPostProcessor() {
13         super();
14         System.out
15                 .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");
16     }
17 
18     // 接口方法、实例化Bean之前调用
19     @Override
20     public Object postProcessBeforeInstantiation(Class beanClass,
21             String beanName) throws BeansException {
22         System.out
23                 .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
24         return null;
25     }
26 
27     // 接口方法、实例化Bean之后调用
28     @Override
29     public Object postProcessAfterInitialization(Object bean, String beanName)
30             throws BeansException {
31         System.out
32                 .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
33         return bean;
34     }
35 
36     // 接口方法、设置某个属性时调用
37     @Override
38     public PropertyValues postProcessPropertyValues(PropertyValues pvs,
39             PropertyDescriptor[] pds, Object bean, String beanName)
40             throws BeansException {
41         System.out
42                 .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
43         return pvs;
44     }
45 }
复制代码

这个有3个方法,其中第二个方法postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。

 

4、演示工厂后处理器接口方法,如下:

复制代码
 1 package springBeanTest;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.config.BeanDefinition;
 5 import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
 6 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 7 
 8 public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
 9 
10     public MyBeanFactoryPostProcessor() {
11         super();
12         System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");
13     }
14 
15     @Override
16     public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
17             throws BeansException {
18         System.out
19                 .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
20         BeanDefinition bd = arg0.getBeanDefinition("person");
21         bd.getPropertyValues().addPropertyValue("phone", "110");
22     }
23 
24 }
复制代码

 

5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:

复制代码
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor">
    </bean>

    <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor">
    </bean>

    <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor">
    </bean>
    
    <bean id="person" class="springBeanTest.Person" init-method="myInit"
        destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州"
        p:phone="15900000000" />

</beans>
复制代码

 

 

6、下面测试一下:

复制代码
 1 package springBeanTest;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class BeanLifeCycle {
 7 
 8     public static void main(String[] args) {
 9 
10         System.out.println("现在开始初始化容器");
11         
12         ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");
13         System.out.println("容器初始化成功");    
14         //得到Preson,并使用
15         Person person = factory.getBean("person",Person.class);
16         System.out.println(person);
17         
18         System.out.println("现在开始关闭容器!");
19         ((ClassPathXmlApplicationContext)factory).registerShutdownHook();
20     }
21 }
复制代码

关闭容器使用的是实际是AbstractApplicationContext的钩子方法。

我们来看一下结果:

复制代码
现在开始初始化容器
2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy
2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml]
这是BeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器!!
这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
【构造器】调用Person的构造器实例化
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用<bean>的init-method属性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
容器初始化成功
Person [address=广州, name=张三, phone=110]
现在开始关闭容器!
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法
复制代码

 

 

 

 

 

/**
*   ————————如果觉得本博文还行,别忘了推荐一下哦,谢谢!
*   作者:钱书康
*   欢迎转载,请保留此段声明。
*   出处:http://www.cnblogs.com/zrtqsk/ 
*/
面试题解答系列:解释Spring框架中bean的生命周期 Bean的生命周期: Bean的定义——Bean的初始化——Bean的使用——Bean的销毁 Bean的定义 Bean 是 spring 装配的组件模型,一切实体类都可以配置成一个 Bean ,进而就可以在任何其他的 Bean 中使用,一个 Bean 也可以不是指定的实体类,这就是抽象 Bean 。 Bean的初始化 Spring中bean的初始化回调有两种方法 一种是在配置文件中声明init-m... 阅读详情

相关推荐

Spring Bean 的生命周期

Spring Bean 的生命周期是指 Bean 从创建到销毁的过程。Spring 容器负责管理 Bean 的生命周期,确保在适当的时机对 Bean 进行初始化和销毁。了解 Bean 的生命周期对于开发者优化和管理 Spring 应用程序至关重要。为了在 Bean 的生命周期中执行自定义逻辑,Spring 提供了多种方式来定义初始化和销毁方法。Spring Bean 的生命周期管理是 Spring 容器的重要功能之一,通过对 Bean 生命周期的深入了解和合理利用,可以有效优化应用程序的性能和资源管理。

FireFox1997 1510

Spring中bean的生命周期

Spring中的bean的生命周期主要包含四个阶段:实例化Bean --> Bean属性填充 --> 初始化Bean -->销毁Bean 首先是实例化Bean,当客户向容器请求一个尚未初始化的bean时,或初始化bean的时候需要注入另一个尚末初始化的依赖时,容器就会调用doCreateBean()方法进行实例化,实际上就是通过反射的方式创建出一个bean对象 Bean实例创建出来后,接着就是给这个Bean对象进行属性填充,也就是注入这个Bean依赖的其它bean对象 属性填充完成后,进行...

kykangyuky的博客 3万+

基于拟蒙特卡洛模拟法的随机潮流计算matlab程序

由式(4-11)可知,蒙特卡洛模拟法的计算量不受电力系统规模大小影响,因此该方法在一些复杂的电力系统中可以得到应用,包括处理电力系统中有多个间歇性新能源接入的问题,解决系统中多个节点之间相关性问题等等。本章在此基础上提出了基于拟蒙特卡洛模拟的随机潮流计算方法,并且对拟蒙特卡洛法中的拟随机数序列进行了改进,大大提高了随机潮流的计算效率。模拟法的具体思路如下:基于实际工程问题的求解需要,建立与之相对应的随机模拟过程和随机概率模型,使得它们的参数,包括概率分布或者数学期望,能够等于问题的实际解;

weixin_47365903的博客 1794

Spring——Bean 的生命周期

目录一、Bean 的生命周期二、代码演示三、主要步骤简述 一、Bean 的生命周期   对于普通的 Java 对象,new 的时候会去创建对象,而当它没有任何引用的时候则被垃圾回收机制回收。相较于前者,由Spring IoC 容器托管的对象,它们的生命周期完全由容器控制。Spring 中每个 Bean 的生命周期如下: 对于 ApplicationContext 容器,当容器启动结束后,实例化所有的 Bean。 设置对象属性,即依赖注入,动态将依赖关系注入到对象中。 紧接着,Spring 会检测该对象

浪漫不死的博客 1万+

LC与RC滤波电路实战对比:从原理到选型指南

本文深入对比了LC与RC滤波电路的核心原理与实战应用。LC滤波利用电感与电容的无损能量搬运,适合高频、大电流电源滤波,效率高但需注意谐振风险;RC滤波通过电阻消耗能量实现滤波,结构简单、成本低,适用于低频信号处理或小电流供电场景。文章提供了从工作原理、性能维度到具体选型的完整指南,帮助工程师根据项目需求(如频率范围、负载电流、效率)做出精准选择。

weixin_29240711的博客 499

AUTOSAR RTE配置实战:从ECU分区到Task映射的完整指南

本文提供了一份AUTOSAR RTE配置的完整实战指南。从创建ECU分区、定义OS任务,到实现Runnable Entity与Task的精确映射,详细解析了每一步的操作要点与常见陷阱。文章结合配置工具界面,旨在帮助开发者高效完成RTE配置,确保系统实时性与数据一致性,是掌握AUTOSAR核心开发流程的实用参考。

weixin_29228203的博客 484

Spring Bean生命周期详解

Spring bean生命周期13个环节 阶段1:Bean元信息配置阶段 阶段2:Bean元信息解析阶段 阶段3:将Bean注册到容器中 阶段4:BeanDefinition合并阶段 阶段5:Bean Class加载阶段 阶段6:Bean实例化阶段(2个小阶段) Bean实例化前阶段 Bean实例化阶段 阶段7:合并后的BeanDefinition处理 阶段8:属性赋值阶段(3个小阶段) B

david_zz2012的专栏 8205

Mamba与iTransformer融合:时间序列预测中的曼巴注意力机制创新实践

本文探讨了Mamba与iTransformer融合在时间序列预测中的创新实践,重点介绍了曼巴注意力机制的设计与优势。通过双路径信息流设计,该方案在保持O(n)复杂度的同时,显著提升了预测精度和训练效率。实验证明,混合架构在电力负荷、气象数据等多变量长序列场景中表现优异,预测误差降低至0.083,内存占用仅4.2GB。

weixin_29292535的博客 219

SpringBean的生命周期

网络上对于spring生命周期的总结很多,对初学者来说看起来眼花缭乱,实际上Spring Bean的生命周期只有四个阶段。把这四个阶段和每个阶段对应的扩展点糅合在一起虽然没有问题,但是这样非常凌乱,难以记忆。要彻底搞清楚Spring的生命周期,首先要把这四个阶段牢牢记住。实例化和属性赋值对应构造方法和setter方法的注入,初始化和销毁是用户能自定义扩展的两个阶段。在这四步之间穿插的各种扩展点,稍后会讲。 实例化 Instantiation 属性赋值 Populate 初始化 Initializati

2万+

分布式光纤传感(DFOS)DTS/DAS/DSS 三合一:10公里管线监测实战与数据解读

本文详细介绍了分布式光纤传感(DFOS)技术在10公里管线监测中的实战应用,通过DTS(温度)、DAS(振动)、DSS(应变)三合一系统,实现对管线健康状态的立体感知。文章涵盖工程部署、数据采集、多物理量数据融合及噪声抑制等关键技术,展示了如何通过一根光纤完成复杂监测任务,显著提升管线安全性和维护效率。

weixin_29168153的博客 315

L型探测器几何畸变矫正

定位像素空间位置 -> 计算水平面投影点 -> 统一物理分辨率 -> 重采样生成新图。

如果想成为中心,那么就到中心去吧。 241

Spring bean生命周期详解

Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。 Spring bean生命周期 四个阶段 Bean的实例化阶段 Bean的设置属性阶段 Bean的 初始化阶段 Bean的销毁阶段 Spring bean生命周期13个环节 阶段1:Bean元信息配置阶段 阶段2:Bean元信息解析阶段 阶段3:将Bean注册到容器中 阶段4:BeanDefinition合并阶段 阶段5:Bean Class加载阶段 阶段6:Bean实例化阶

weixin_44145478的博客 1万+

LLaMA Factory添加新模型template的实战解析

本文主要介绍了LLaMA Factory添加新模型template的实战解析,希望对使用大语言模型的同学们有所帮助。 文章目录 1. 前言 2. 实战解析 2.1 检查代码 2.2 修改代码

herosunly的博客 19万+

【Spring】Spring的Bean的生命周期

在Java中,Bean是一个重要的概念,它代表了应用程序中的一个对象。在开发中,我们经常使用Bean来管理对象的生命周期。本文将介绍Bean的生命周期,并详细讲解如何在Spring框架中管理Bean的生命周期。Spring其实就是一个管理Bean对象的工厂。它负责对象的创建,对象的销毁等。所谓的生命周期就是:对象从创建开始到最终销毁的整个过程。Spring为每个Bean定义了若干个回调方法,使得开发人员可以在某个特定的时间点对Bean进行特定的操作。

qq_46096136的博客 1万+

华为OD机试真题 新系统 - 8位LED控制器 (Java/Py/C/C++/Js/Go)

本文整理华为 OD 机试新系统机考真题库,涵盖高频考点精析与完整题目内容,提供 C 语言、Java、C++、Python、Go、JavaScript 多语言源码实现,搭配详细解题思路讲解,并支持在线 OJ 刷题练习,助力高效备考华为 OD 机试新系统。

算法大师! 1975

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Spring 中Bean 的生命周期

Spring 中Bean 的生命周期 文章目录Spring 中Bean 的生命周期前言一、Bean 的完整生命周期二、Bean 的生命周期验证 前言 ​ 这其实是一道面试题,是我在面试百度的时候被问到的,当时没有答出来(因为自己真的很菜),后来在网上寻找答案,看到也是一头雾水,直到看到了《Spring in action》这本书,书上有对Bean声明周期的大致解释,但是没有代码分析,所以就自己上...

程序员cxuan的个人主页 7680

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Spring中Bean的生命周期

说明:postProcessAfterInstantiation之后就可以操作目标Bean了,postProcessProperties是针对Spring 配置文件中property属性的配置进行编辑,而在postProcessProperties与postProcessBeforeInitialization之间完成了属性的注入,包括依赖注入、@Value注入等,后续就是对Bean进行Getter、Setter调用来设置bean的上下文、字段值。我的目标是为读者提供有深度、有实用价值的技术洞察与分析。

沉淀所学,分享所思,让热爱与成长同行。商务记录AI实战经验,助力开发者快速成长。 热爱AI,希望做出有影响力的技术成果。 技术点亮生活,分享连接价值与机会。 专注AI落地实战,陪你走好技术每一步。 1万+

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 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 Bean 生命周期

一、Spring核心模块介绍 1. Spring Core: Core封装包是框架的最基础部分,提供IOC和依赖注入特性。这里的基础概念是BeanFactory,它提供对Factory模式的经典实现来消除对程序性单例模式的需要,并真正地允许你从程序逻辑中分离出依赖关系和配置。 2.Spring Context: 构建于Core封装包基础上的 Context封装包,提供了一种框架式的对象访问方法,有些象JNDI注册器。Context封装包的特性得自于Beans封装包,并添加了对国际化(I18N).

fox_bert的博客 4697

spring中bean的生命周期

一、简介 理解spring中bean的生命周期,对于学习和使用spring很有帮助。本文将从两个角度对spring中bean 的生命周期进行介绍,一是bean定义生成;二是bean在初始化、使用、销毁的生命周期中经历的阶段。二、bean定义生成 bean定义生成主要分为三个步骤,即bean定义的获取、bean定义的注册。1、bean定义的获取 bean的定义来源各种各样,如xml定义、java注解...

panda-star的博客 3万+

【框架篇】Bean作用域和生命周期

本文核心: 1,Bean作用域的介绍? 2,Bean作用域的设置? 3,Bean生命周期流程?

小杨的博客 1052

Spring容器中bean的生命周期

在传统的Java应用中,bean的生命周期很简单。使用Java关键字new进行bean实例化,然后该bean就可以使用了。一旦该bean不再被使用,则由Java自动进行垃圾回收。相比之下,Spring容器中的bean的生命周期就显得相对复杂多了。正确理解Spring bean的生命周期非常重要,因为你或许要利用Spring提供的扩展点来自定义bean的创建过程。下图展示了bean装载到Spring...

ThinkWon的博客 1万+

Spring 框架中 Bean 的生命周期详解

完整生命周期:实例化 -> 属性赋值 -> BeanPostProcessor 的前置处理 -> 初始化 -> BeanPostProcessor 的后置处理 -> 使用 -> 销毁。

青灯文案的博客 1147

深入了解《Spring框架中Bean的生命周期》

在 Spring 框架中,Bean 是由 Spring IoC 容器管理的对象。创建出来的这些对象由容器实例化、组装和管理。毫不夸张的说,Bean 是构成应用程序主干并由 Spring IoC 容器管理的对象。所以说,在Spring框架中,Bean是非常重要的,那么今天我们就来深入了解一下bean的生命周期。

2401_85973273的博客 921

Spring Bean的生命周期(非常详细)

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。  转载请注明地址 http://www.c

每天进步一点点! 1万+

Spring学习笔记06——bean、java bean、spring bean、POJO几个概念讲解

Bean这个词的具体含义需要根据上下文来区分,它可能指Java Bean(标准Java规范)或(Spring框架中的概念)。POJO是普通 Java 对象,强调简单性。Java Bean是标准化 POJO,强调规范与兼容性。Java Bean一定是POJO,但POJO不一定是Java Bean,Java Bean的规范更严格,POJO 更自由,例如Java Bean有Getter/Setter,并且必须有无参构造器,而POJO不必须。

weixin_42844704的博客 1489
上一篇: Java后台框架篇--Spring应用上下文配置:Xml方式
下一篇: Java后台框架篇--Spring框架中模块组成
咸鱼的梦想
博客等级 码龄11年 99粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值