zoukankan      html  css  js  c++  java
  • Java框架spring 学习笔记(四):BeanPostProcessor接口

    如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化前后后添加一些自己的逻辑处理

    编写InitHelloWorld.java

     1 package com.example.spring;
     2 
     3 import org.springframework.beans.BeansException;
     4 import org.springframework.beans.factory.config.BeanPostProcessor;
     5 
     6 public class InitHelloWorld implements BeanPostProcessor{
     7     //初始化Bean前
     8     @Override
     9     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    10         System.out.println("Befor Initialization :"+beanName);
    11         return bean;
    12     }
    13 
    14     //初始化Bean后
    15     @Override
    16     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    17         System.out.println("After Initialization :"+beanName);
    18         return bean;
    19     }
    20 }

    编写Beans.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     5 
     6     <bean id="helloWorld" class="com.example.spring.HelloWorld"
     7           init-method="init" destroy-method="destroy">
     8         <property name="message" value="Hello World"></property>
     9     </bean>
    10 
    11     <bean class="com.example.spring.InitHelloWorld"></bean>
    12 </beans>

    编写HelloWorld.java

     1 package com.example.spring;
     2 
     3 public class HelloWorld {
     4     private String message;
     5     public void setMessage(String message){
     6         this.message  = message;
     7     }
     8 
     9     public void getMessage(){
    10         System.out.println("Your Message : " + message);
    11     }
    12     //定义初始化方法
    13     public void init(){
    14         System.out.println("Bean is going through init.");
    15     }
    16     //定义销毁方法
    17     public void destroy(){
    18         System.out.println("Bean will destroy now.");
    19     }
    20 }

    运行输出

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

    可以看到初始化bean的前后分别调用了postProcessBeforeInitialization和postProcessAfterInitialization方法

  • 相关阅读:
    poj 2406 Power Strings【最小循环节】
    hdoj 2087 剪花布条
    hdoj 1054 Strategic Game【匈牙利算法+最小顶点覆盖】
    hdoj 1151 Air Raid
    hdoj 2502 月之数
    hdoj 1862 EXCEL排序
    hdoj 1200 To and Fro
    hdoj 1150 Machine Schedule【匈牙利算法+最小顶点覆盖】
    hdoj 1068 Girls and Boys【匈牙利算法+最大独立集】
    uva1563
  • 原文地址:https://www.cnblogs.com/zylq-blog/p/7793144.html
Copyright © 2011-2022 走看看