代码之家  ›  专栏  ›  技术社区  ›  Kevin Pauli

在Spring中,比如“init方法”,但在注入依赖项之后调用?

  •  10
  • Kevin Pauli  · 技术社区  · 16 年前

    这太疯狂了…已经使用Spring一段时间了,但是找不到像“init方法”这样的在注入所有依赖项之后被调用的方法。

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

    3 回复  |  直到 12 年前
        1
  •  21
  •   Jose Diaz    16 年前

    对于Spring2.5及更高版本,如果对象在初始化时需要调用回调方法,则可以使用 @PostConstruct 注释。

    例如:

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

    这比 BeanPostProcessor 方法。

        2
  •  4
  •   GreenGiant WoodenKitty    12 年前

    据我所知, 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
  •  3
  •   Teja Kantamneni    16 年前

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