Spring Bean 后置处理器


当前第2页 返回上一页

这里是 InitHelloWorld.java 文件的内容:

package com.tutorialspoint;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
public class InitHelloWorld implements BeanPostProcessor {
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("BeforeInitialization : " + beanName);
    return bean; // you can return any other object as well
  }
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("AfterInitialization : " + beanName);
    return bean; // you can return any other object as well
  }
}

下面是 MainApp.java 文件的内容。在这里,你需要注册一个在 ?AbstractApplicationContext? 类中声明的关闭? hook? 的 ?registerShutdownHook() ?方法。它将确保正常关闭,并且调用相关的 ?destroy? 方法。

package com.tutorialspoint;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
  public static void main(String[] args) {
    AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
    obj.getMessage();
    context.registerShutdownHook();
  }
}

下面是 ?init? 和 ?destroy? 方法需要的配置文件 Beans.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
?
<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">
?
  <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"
      init-method="init" destroy-method="destroy">
      <property name="message" value="Hello World!"/>
  </bean>
?
  <bean class="com.tutorialspoint.InitHelloWorld" />
?
</beans>

一旦你创建源代码和 ?bean? 配置文件完成后,我们就可以运行该应用程序。如果你的应用程序一切都正常,将输出以下信息:

BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.



标签:Spring IoC

返回前面的内容

相关阅读 >>

spring beanfactory 容器

spring bean 定义继承

spring 自动装配 bytype

spring 注入集合

spring 中基于 aop 的 @aspectj

spring bean 作用域

spring 基于设值函数的依赖注入

spring 声明式事务管理

spring @autowired 注释

spring 基于 java 的配置

更多相关阅读请进入《Spring IoC》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...