bean的callbacks(初始化,销毁bean)

方法一:

1 初始化bean

a 使用bean的init-method属性调用相应的方法初始化

  <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

  public class ExampleBean {

    public void init() {

      // do some initialization work

    }

  }

 

b 使用org.springframework.beans.factory.InitializingBean接口的void afterPropertiesSet() throws Exception;方法初始化

  <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

  public class AnotherExampleBean implements InitializingBean {

    public void afterPropertiesSet() {

      // do some initialization work

    }

  }

 

2 销毁bean

a 使用bean的destroy-method属性调用相应的方法销毁

  <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

  public class ExampleBean {

    public void cleanup() {

      // do some destruction work (like releasing pooled connections)

    }

  }

b 使用org.springframework.beans.factory.DisposableBean接口的void destroy() throws Exception;方法销毁

  <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

  public class AnotherExampleBean implements DisposableBean {

    public void destroy() {

      // do some destruction work (like releasing pooled connections)

    }

  }

说明:使用bean的属性调用方法的时候将增加代码的耦合度

 

方法二:

使用beans的default-init-method(default-destroymethod)属性回调创建(销毁)bean的方法。当创建一个新的bean的时候,IOC容器就会在适当的时候调用init方法

public class DefaultBlogService implements BlogService {
private BlogDao blogDao;
public void setBlogDao(BlogDao blogDao) {
this.blogDao = blogDao;
}
// this is (unsurprisingly) the initialization callback method
public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
}
<beans default-init-method="init">
<bean id="blogService" class="com.foo.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>

 

方法三:

使用注解的方式@PostConstruct and @PreDestroy

 

特别说明:当以上三种方法在同一个bean中都配置后,三种初始化(销毁)方法都会执行。其中执行顺序是首先是注解方式,然后是实现接口方式,最后是在beans中配置的。

转载于:https://www.cnblogs.com/JavaTWW/p/4808070.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值