spring模块(二)SpringBean(2)InitializingBean

发布于:2024-07-02 ⋅ 阅读:(13) ⋅ 点赞:(0)

一、介绍

1、简介

InitializingBean是Spring框架提供的一个接口,用于在Bean初始化完成后执行特定的初始化逻辑。

Spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用。

2、和init-method关系与比较

(1)实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率要高一点,但是init-method方式消除了对spring的依赖。

(2)如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。

二、使用

1、使用方法
1.1、实现InitializingBean接口

可以让Bean实现该接口,并重写其afterPropertiesSet()方法

1.2、注册

也即让bean初始化。方法有:

(1)@Component 及其拓展注解如@Controller、@Service、@Repository、@Configuration;

(2)@Bean注解

2、执行顺序

(1)构造方法 > postConstruct >afterPropertiesSet > init方法;

(2)在Spring初始化bean的时候,如果该bean实现了InitializingBean接口,并且同时在配置了init-method,系统则是先调用afterPropertieSet()方法,然后再调用init-method中指定的方法。

3、demo

例1:

package org.example.bean.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.service.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService, InitializingBean {

    List<String> typeList = new ArrayList<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("UserServiceImpl初始化完成......");
        typeList.add("1");
        typeList.add("2");
    }

    @Override
    public void listTypes() {
        log.info("typeList={}",typeList);
    }
}

启动打印:

单元测试调用接口 

 @Test
    public void test(){
      userService.listTypes();
    }

打印: