Spring接口

来源:互联网 发布:淘宝上的拍卖靠谱吗 编辑:程序博客网 时间:2024/06/05 04:35

InitializingBean

当一个类被Spring加载的时候,首先调用init方法,如果实现了InitializingBean的时候,会调用afterPropertiesSet方法,可以在方法里面执行代码

public class ExampleBean implements InitializingBean {   public void afterPropertiesSet() {      // do some initialization work   }}

可以在Spring配置文件里面配置init-method

<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>
public class ExampleBean {   public void init() {      // do some initialization work   }}

DisposableBean

销毁回调,当Spring的Bean容器销毁之前,会回调destroy方法

public class ExampleBean implements DisposableBean {   public void destroy() {      // do some destruction work   }}

在基于XML的配置元数据的情况下,可以使用destroy-method属性来指定具有void no-argument签名的方法的名称

<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>
public class ExampleBean {   public void destroy() {      // do some destruction work   }}

registerShutdownHook

Spring关闭Bean容器,可以使用registerShutdownHook()

public static void main(String[] args) {      AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");      obj.getMessage();      context.registerShutdownHook();   }

如果想要让所有的Bean都配置初始化方法和销毁方法,可以在Spring的配置文件中配置全局的方法default-init-method = "init"default-destroy-method = "destroy"

<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-3.0.xsd"   default-init-method = "init"    default-destroy-method = "destroy">   <bean id = "..." class = "...">      <!-- collaborators and configuration for this bean go here -->   </bean></beans>

BeanPostProcessor

如果我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。
这里写图片描述

public class MyBeanPostProcessor implements BeanPostProcessor {       public MyBeanPostProcessor() {          super();          System.out.println("这是BeanPostProcessor实现类构造器!!");               }       @Override       public Object postProcessAfterInitialization(Object bean, String arg1)               throws BeansException {           System.out.println("bean处理器:bean创建之后..");           return bean;       }       @Override       public Object postProcessBeforeInitialization(Object bean, String arg1)               throws BeansException {           System.out.println("bean处理器:bean创建之前..");           return bean;       }   }  
原创粉丝点击