日志 spring Bean 实例化

snj*_*egi 6 java spring

我们如何在 Spring 中记录每个 bean 实例化?

  • 我希望每次初始化 bean 时都记录一条消息。
  • 我有 N 个 bean,我不想在每个 bean 的 init 方法上放置任何记录器。
  • 我认为这是一个跨领域的问题,但不确定如何实现这一点。

有没有办法。?

yas*_*nth 9

你可以使用一个 BeanPostProcessor

@Component
public class LogBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {
        LOGGER.log(String.format("Bean instantiated with name %s and class %s", beanName, bean.getClass().getSimpleName()));
        return bean;
    }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*hta -1

您可以使用 Spring 的事件监听器(此处进行了解释)来监听事件。我相信您需要听的事件是ContextRefreshedEvent,例如:

@Component
public class MyListener 
        implements ApplicationListener<ContextRefreshedEvent> {

    public void onApplicationEvent(ContextRefreshedEvent event) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)