【问题标题】:Something in Spring like 'init-method' but called after dependencies are injected?Spring 中的类似“init-method”但在注入依赖项后调用的东西?
【发布时间】:2011-03-28 23:58:00
【问题描述】:

这太疯狂了...使用 Spring 已经有一段时间了,但找不到像在注入所有依赖项后调用的“init-method”之类的东西。

我看到了 BeanPostProcessor 东西,但我正在寻找一种轻量级且非侵入性的东西,它不会将我的 bean 与 Spring 耦合。就像 init 方法一样!

【问题讨论】:

    标签: spring


    【解决方案1】:

    在 Spring 2.5 及更高版本中,如果对象需要在初始化时调用回调方法,则可以使用 @PostConstruct 注释对该方法进行注释。

    例如:

    public class MyClass{
    
       @PostConstruct
       public void myMethod() {
         ...
       }
       ...
    } 
    

    这比BeanPostProcessor 方法的侵入性要小。

    【讨论】:

    • 但是在构建我的 pojos 时我必须在构建路径中包含 Spring ......没有仅限 XML 的方法吗?
    • 没关系,我看到 @PostConstruct 在 javax.annotation 包中。谢谢!
    • 如果您有循环依赖,请在此处查看 cmets 中的一些注意事项:stackoverflow.com/a/3406631/32453
    【解决方案2】:

    据我所知,the init-method is called after all dependencies are injected。试试看:

    public class TestSpringBean
    {
        public TestSpringBean(){
            System.out.println( "Called constructor" );
        }
    
        public void setAnimal( String animal ){
            System.out.println( "Animal set to '" + animal + "'");
        }
    
        public void setAnother( TestSpringBean another ){
            System.out.println( "Another set to " + another );
        }
    
        public void init(){
            System.out.println( "Called init()" );
        }
    }
    
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    
        <bean id="myBean" class="TestSpringBean" init-method="init">
            <property name="animal" value="hedgehog" />
            <property name="another" ref="depBean" />
        </bean>
    
        <bean id="depBean" class="TestSpringBean"/>
    
    </beans>
    

    这会产生:

    Called constructor
    Called constructor
    Animal set to 'hedgehog'
    Another set to com.et.idp.wf.integration.TestSpringBean@7d95d4fe
    Called init()
    

    【讨论】:

      【解决方案3】:

      你需要实现InitializingBean接口并重写afterPropertiesSet方法。

      【讨论】:

      • 但是在构建我的 pojo 时,我必须在构建路径中包含 Spring ......没有仅限 XML 的方式吗?
      猜你喜欢
      • 2012-07-07
      • 2014-06-04
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 2019-03-17
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多