Spring中Bean创建完成后执行指定代码的几种实现方式

7次阅读

共计 1580 个字符,预计需要花费 4 分钟才能阅读完成。

在实际开发中经常会遇到在 spring 容器加载完某个 bean 之后,需要执行一些业务代码的场景。比如初始化配置、缓存等。有以下几种方式可以实现此需求(欢迎补充)

实现 ApplicationListener 接口

实现 ApplicationListener 接口并实现方法 onApplicationEvent() 方法,Bean 在创建完成后会执行 onApplicationEvent 方法

@Component
public class DoByApplicationListener implements ApplicationListener<ContextRefreshedEvent> {public DoByApplicationListener() {System.out.println("DoByApplicationListener constructor");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {if (event.getApplicationContext().getParent() == null) {System.out.println("DoByApplicationListener do something");
        }
    }
}

实现 InitializingBean 接口

实现 InitializingBean 接口并实现方法 afterPropertiesSet(),Bean 在创建完成后会执行 afterPropertiesSet() 方法

@Component
public class DoByInitializingBean implements InitializingBean {public DoByInitializingBean() {System.out.println("DoByInitializingBean constructor");
    }

    @Override
    public void afterPropertiesSet() throws Exception {System.out.println("InitByInitializingBean do something");
    }
}

使用 @PostConstruct 注解

在 Bean 的某个方法上使用 @PostConstruct 注解,Bean 在创建完成后会执行该方法

@Component
public class DoByPostConstructAnnotation {public DoByPostConstructAnnotation() {System.out.println("DoByPostConstructAnnotation constructor");
    }

    @PostConstruct
    public void init(){System.out.println("InitByPostConstructAnnotation do something");
    }
}

使用 init-method

使用 init-metod 可以指定 Bean 在创建完成后,初始化使用的方法,比如有个 Bike 类

public class Bike {public Bike() {System.out.println("Bike constructor");
    }
    public void initBike() {System.out.println("Bike do something");
    }
}

使用 @Configuration 注解来启动容器,并设置 Bike 的初始化方法为 initBike

@Configuration
public class DoByInitMethod {@Bean(initMethod ="initBike")
    public Bike bike() {return new Bike();
    }
}

以上方式和代码全部都测试运行过,绝对可用!

正文完
 0