草庐IT

Spring IOC官方文档学习笔记(六)之自定义bean的特性

shame11 2023-04-16 原文

1.生命周期回调

(1) 如果我们想要介入bean的生命周期,可通过实现spring中的InitializingBean和DisposableBean接口来达到这一目的,spring会调用InitializingBean中的afterPropertiesSet()以及DisposableBean中的destroy()方法来执行bean在初始化和销毁时所要执行的行为,此外JSR-250规范中的@PostConstruct和@PreDestroy注解也同样对spring bean适用,它们也可以指定bean的初始化或销毁方法,且不与spring框架强耦合,同时如果不想使用JSR-250注解,也可通过配置bean中的init-method和destroy-method属性来指定初始化或销毁回调。以上这些所有的回调都会由BeanPostProcessor来进行统一调用处理,因此如果我们有些需求无法通过这些生命周期回调实现,那么可以考虑自定义BeanPostProcessor。

(2) 除了初始化,销毁回调外,我们还可以实现Lifecycle接口,来让bean参与到容器级别的生命周期,比如容器的启动或关闭等

(3) 初始化回调(Initialization Callbacks):用于指定在容器设置了bean的所有所需属性后,应该执行的行为,它作用于原始bean上,即AOP代理对象不会被执行这些初始化回调,共有3种方式,分别为实现InitializingBean接口,使用@PostConstruct注解或在xml文件中指定init-method属性,如下所示

public class ExampleA implements InitializingBean {

    /**
     * InitializingBean接口提供的方法,不建议使用,因为它会与spring框架强耦合
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet...");
    }

    @PostConstruct
    public void postConstruct() {
        System.out.println("postConstruct...");
    }

    //将该方法于xml配置文件中指定
    public void init() {
        System.out.println("init...");
    }
}

<!-- xml配置文件 -->
<beans ...>
    <!-- 注意:如果是基于xml的配置,则要使@PostConstruct注解生效,则要开启注解扫描 -->
    <context:annotation-config />

    <!-- 使用bean标签中的init-method属性来指定bean中的初始化回调 -->
    <bean id="exampleA" class="cn.example.spring.boke.ExampleA" init-method="init"></bean>
</beans>

//之后,启动容器,获取这个bean,日志打印如下:
postConstruct...
afterPropertiesSet...
init...

由上可见,初始化回调的执行顺序为:@PostConstruct注解所标注的方法 -> InitializingBean接口中的afterPropertiesSet()方法 -> init-method属性所指定的方法

(4) 销毁回调(Destruction Callbacks):用于容器在销毁bean之前,应该执行的行为,有3种方式,分别为实现DisposableBean接口,使用@PreDestroy注解或在xml文件中指定destroy-method属性,如下所示

public class ExampleA implements DisposableBean {

    /**
     * DisposableBean接口提供的方法,不建议使用,因为它会与spring框架强耦合
     */
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean...");
    }

    @PreDestroy
    public void preDestroy() {
        System.out.println("preDestroy...");
    }

    //将该方法于xml配置文件中指定
    public void cleanup() {
        System.out.println("cleanup...");
    }
}

<!-- xml配置文件 -->
<beans ...>
    <context:annotation-config />

    <!-- 使用bean标签中的destroy-method属性来指定bean中的销毁回调 -->
    <bean id="exampleA" class="cn.example.spring.boke.ExampleA" destroy-method="cleanup"></bean>
</beans>

//之后,启动并关闭容器,日志打印如下:
preDestroy...
DisposableBean...
cleanup...

由上可见,销毁回调的执行顺序为:@PreDestroy注解所标注的方法 -> DisposableBean接口中的destroy()方法 ->destroy-method属性所指定的方法,与初始化回调的执行顺序是相似的

(5) 自定义默认的初始化和销毁回调:我们可以使用一致的初始化方法名和销毁方法名,然后将其设置为beans标签中default-init-method和default-destroy-method的属性值,这样就不用给每个bean设置init-method和destroy-method属性了,方便统一和简化代码,如下

//统一规定每个bean的初始化方法名为init,销毁方法名为destroy
public class ExampleA {
    public void init() {
        System.out.println("init...");
    }

    public void destroy() {
        System.out.println("destroy...");
    }
}

<!-- xml配置文件 -->

<!-- 使用beans标签的default-init-method和default-destroy-method属性,来配置统一的默认初始化和销毁方法,相当于给该beans标签下的每个bean标签都添加了init-method="init"和destroy-method="destroy"属性 -->
<beans  ....
        default-init-method="init"
        default-destroy-method="destroy">
    <!-- 下面这个标签等价于<bean id="exampleA" class="cn.example.spring.boke.ExampleA" init-method="init" destroy-method="destroy"></bean>  -->
    <bean id="exampleA" class="cn.example.spring.boke.ExampleA"></bean>

    <!-- 此外,如果我们想单独配置某个bean的初始化或销毁方法,直接显式指定它的init-method和destroy-method属性就可以,它会覆盖掉beans标签中的默认配置 -->
</beans>

(6) 如果我们期望bean能够参与到容器的生命周期,比如让我们的bean在容器启动或关闭时执行某些方法,那么我们就可以使用Lifecycle接口来实现。任何的bean都可以实现该接口,在IOC容器接收到启动或停止信号(例如在运行时停止/重启容器)时,它会找出其中所有实现了LifeCycle接口或其子接口的bean,并执行相应的回调。IOC容器是通过生命周期处理器LifecycleProcessor来实现这一功能的,此外还需注意,如果没有对容器显式的调用start或close等方法,则实现LifeCycle接口的类不会被回调,此时可应该使用SmartLifecycle,如下所示

//Lifecycle接口,它提供了3个方法
public interface Lifecycle {

    /**
     * 容器启动(start)时执行的回调
     */
    void start();
    
    /**
     * 容器停止(stop)时执行的回调,注意在某些情况(hot refresh during a context’s lifetime)下该回调不保证被调用
     */
    void stop();
    
    /**
     * 用于判断当前容器是否正在运行,注意:只有该方法返回false时,start方法才会被执行;只有该方法返回true时,stop方法才会被执行
     */
    boolean isRunning();
}

//实现Lifecycle接口
public class ExampleA implements Lifecycle {
    
    //注意这里running初始化为false,如果它为true,那么start方法就不会执行,只会执行stop方法
    private boolean running = false;
   
    @Override
    public void start() {
        this.running = true;
        System.out.println("start...");
    }
    
    @Override
    public void stop() {
        this.running = false;
        System.out.println("stop...");
    }
    
    @Override
    public boolean isRunning() {
        return this.running;
    }
}

<!-- xml配置文件 -->
<beans ....>
    <bean id="exampleA" class="cn.example.spring.boke.ExampleA" ></bean>
</beans>

//测试一:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
ExampleA exampleA = (ExampleA)ctx.getBean("exampleA");
//启动容器,会向容器发送启动信号
ctx.start();
System.out.println(exampleA.isRunning());
//关闭容器,会向容器发送停止信号
ctx.close();
System.out.println(exampleA.isRunning());

//控制台输出如下,可见在容器容器或关闭时,执行了exampleA的相应回调
start...
true
stop...
false

//测试二:不对容器显式的调用start或close方法,即将start和close方法注释掉
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
ExampleA exampleA = (ExampleA)ctx.getBean("exampleA");
//ctx.start();
System.out.println(exampleA.isRunning());
//ctx.close();
System.out.println(exampleA.isRunning());

//控制台输出如下,可见如果不显式调用容器的start或close方法,则实现LifeCycle接口的类(此例为exampleA)不会被回调,此时可以使用SmartLifecycle
false
false

当bean使用了SmartLifecycle后,如下

//SmartLifecycle继承自Lifecycle和Phased,不仅同样提供了Lifecycle中的3个方法,还提供了3个默认方法
public interface SmartLifecycle extends Lifecycle, Phased {
    int DEFAULT_PHASE = 2147483647;
    
    /**
     * 是否开启自动回调,如果这里返回false,那么就跟直接实现Lifecycle接口一致,触发回调需要我们显示的调用容器的start或stop方法
     */
    default boolean isAutoStartup() {
        return true;
    }
    
    /**
     * 进行异步关闭
     */
    default void stop(Runnable callback) {
        this.stop();
        callback.run();
    }
    
    /**
     * 确定不同bean的回调的执行顺序,如果这个返回值越大,就越后执行,越先停止
     */
    default int getPhase() {
        return 2147483647;
    }
}

public class ExampleA implements SmartLifecycle {

    private boolean running = false;

    @Override
    public void start() {
        this.running = true;
        System.out.println("start...");
    }

    @Override
    public void stop() {
        this.running = false;
        System.out.println("stop...");
    }

    @Override
    public boolean isRunning() {
        return this.running;
    }
}

//测试
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
ExampleA exampleA = (ExampleA)ctx.getBean("exampleA");
System.out.println(exampleA.isRunning());

//控制台输出如下,可见启动时容器自动进行了回调,而关闭则需要我们显式的调用close方法才会执行回调
start...
true

对于多个bean,如果我们期望一个bean能先于另一个bean执行回调,则可通过SmartLifecycle中getPhase()方法的返回值来指定执行顺序,具体规则如下

public class ExampleA implements SmartLifecycle {

    private boolean running = false;

    @Override
    public void start() {
        this.running = true;
        System.out.println("exampleA start...");
    }

    @Override
    public void stop() {
        this.running = false;
        System.out.println("exampleA stop...");
    }

    @Override
    public boolean isRunning() {
        return this.running;
    }
    
    @Override
    public int getPhase() {
        return 1;
    }
}

public class ExampleB implements SmartLifecycle {

    private boolean running = false;

    @Override
    public void start() {
        this.running = true;
        System.out.println("ExampleB start...");
    }

    @Override
    public void stop() {
        this.running = false;
        System.out.println("ExampleB stop...");
    }

    @Override
    public boolean isRunning() {
        return this.running;
    }

    @Override
    public int getPhase() {
        return 0;
    }
}

//测试
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
ctx.close();

//结果如下,可见一个bean的getPhase()方法返回值越小,就越先执行,越后停止,反之,如果返回值越大,就越后执行,越先停止
ExampleB start...
exampleA start...
exampleA stop...
ExampleB stop...

(7) 关闭Spring IOC容器:如果我们在非web环境中使用IOC容器(即只单纯的使用了IOC容器,而没有使用Spring Web MVC等其他功能),记得要向JVM注册一个关闭钩子,以便优雅的关闭Spring IOC容器,它会执行singleton bean上的销毁回调,释放所有资源,如下

public static void main(String[] args) {
  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
  //使用registerShutdownHook方法向JVM注册一个关闭钩子(回调)
  ctx.registerShutdownHook();

  /**
   * 应用代码...
   */

  //结束,此时关闭钩子会被调用,销毁IOC容器中的所有资源
}

2.ApplicationContextAware与BeanNameAware

(1) ApplicationContextAware用于获取ApplicationContext对象,即Spring IOC容器,如下

//应该尽量避免使用ApplicationContextAware,因为这会将Spring框架与我们的代码强耦合,同时也破坏了控制反转编程模式,变成了我们自己去拉取容器中的bean
public class ExampleA implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    public void doSomething() {
        //使用applicationContext,即IOC容器,从中检索其他的bean
        ExampleB exampleB = this.applicationContext.getBean(ExampleB.class);
        System.out.println(exampleB);
    }
    
    //Spring会回调该方法并将ApplicationContext注入给bean exampleA
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

此外,也可以不用实现ApplicationContextAware接口,而是通过Spring的自动装配功能来注入ApplicationContext对象,如下

public class ExampleA {

    private ApplicationContext applicationContext;
    
    //提供setter方法,用于依赖注入
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void doSomething() {
        ExampleB exampleB = this.applicationContext.getBean(ExampleB.class);
        System.out.println(exampleB);
    }
}

public class ExampleB { }

<!-- xml配置文件 -->
<beans ...>

    <!-- 使用autowire属性,开启自动装配 -->
    <bean id="exampleA" class="cn.example.spring.boke.ExampleA" autowire="byType"></bean>

    <bean id="exampleB" class="cn.example.spring.boke.ExampleB"></bean>
</beans>

(2) BeanNameAware用于获取该bean的名称

public class ExampleA implements BeanNameAware {

    private String name;
    
    //Spring会回调该方法并将该bean的名称进行注入
    @Override
    public void setBeanName(String s) {
        this.name  = s;
    }
}

<!-- xml配置文件 -->
<beans ...>
    <!-- 这里指定了exampleA的id为aaa,那么在上面的回调中Spring会将aaa注入给exampleA -->
    <bean id="aaa" class="cn.example.spring.boke.ExampleA"></bean>
</beans>

3.其他Aware接口

(1) 以Aware为后缀的接口,通常是用来向bean中注入某些容器组件的,比如上面所提到的ApplicationContextAware接口用来向容器中注入ApplicationContext对象,Spring还提供了很多其他的Aware接口,详见官方文档

有关Spring IOC官方文档学习笔记(六)之自定义bean的特性的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  7. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

  8. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  9. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  10. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

随机推荐