首页 > 其他分享 >BeanPostProcessor接口 和 InitializingBean接口

BeanPostProcessor接口 和 InitializingBean接口

时间:2023-03-03 17:02:02浏览次数:33  
标签:BeanPostProcessor InitializingBean System 接口 bean println public out

相同点:

  1. 必须都被spring容器管理(对应注解或xml中配置bean),接口中的方法才会被使用生效;
  2. 都是在bean实例化过程中调用接口对应的方法;

不同点:
InitializingBean
作用对象:只针对该接口的实现类bean;

BeanPostProcessor
作用对象:spring容器管理的所有bean;或可以在方法中自定义选择特定的bean处理业务逻辑

执行顺序:构造器->postProcessBeforeInitialization->@PostConstruct->afterPropertiesSet()->init-method属性->postProcessAfterInitialization

代码举例:

@Data
@ToString
public class Cart implements InitializingBean {

    public Cart() {
        System.out.println("构造器");
    }

    @FieldMapping("ID")
    private Integer id;

    @FieldMapping("DESC-lq")
    private String desc;

    @PostConstruct
    public void init() {
        System.out.println("init:" + this.getId());
    }

    private void initMethod() {
        System.out.println("initMethod:" + this.getId());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("initializingBean:" + this.getId());
    }
}

@Configuration
public class CartConfiguration {

    @Bean(initMethod = "initMethod")
    public Cart cart() {
        return new Cart();
    }
}

@Component
public class BeanPostProcessorImpl implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization: " + beanName);
        return bean;
    }
}

标签:BeanPostProcessor,InitializingBean,System,接口,bean,println,public,out
From: https://www.cnblogs.com/rbwbear/p/17176120.html

相关文章