spring @Component @Scope("singleton") 公共类 BootStrapper 实现 ApplicationListener<ContextStartedEvent> {

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15271019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:47:34  来源:igfitidea点击:

@Component @Scope("singleton") public class BootStrapper implements ApplicationListener<ContextStartedEvent> {

springweb-applications

提问by Chandana Sapparapu

I am trying to do a one time initialization of my webapp. I need a singleton for the ApplicationListener class, so I set the scope to Singleton, but it is creating multiple instances. This BootStrapper is not defined in any other xml config files. I know that the default scope is singleton, but had to add @Scope("singleton") because it was not a singleton. Even with this annotation, it still creates multiple instances. Here is my ApplicationListener.

我正在尝试对我的 webapp 进行一次初始化。我需要 ApplicationListener 类的单例,所以我将范围设置为单例,但它正在创建多个实例。此 BootStrapper 未在任何其他 xml 配置文件中定义。我知道默认范围是单例,但必须添加 @Scope("singleton") 因为它不是单例。即使有了这个注解,它仍然会创建多个实例。这是我的 ApplicationListener。

@Component
@Scope("singleton")
public class BootStrapper implements ApplicationListener<ContextRefreshedEvent> {

Am I missing anything?

我错过了什么吗?

回答by Ralph

To have a callback that is invoked after the bean is initialized, use @PostConstruct.

要在 bean 初始化后调用回调,请使用@PostConstruct.

@Component
public class BootStrapper() {

     @PostConstruct
     public void doSomething() {
          System.out.println("I am initalized!");
     }
}

回答by Nadhu

Try like this:

像这样尝试:

@Configuration
public class TestService
{
  private Properties properties;

  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
  public Properties getAppProperties()
  {
    try
    {
        if (properties == null)
        {
          properties = ServiceUtils.loadProperties();
        }
     return properties;
    }
    catch (Exception e)
    {
      LOGGER.logCaughtException("Exception Occured while loading App Properties.", e);
    }
  }
}