【问题标题】:@Component @Scope("singleton") public class BootStrapper implements ApplicationListener<ContextStartedEvent> {@Component @Scope("singleton") 公共类 BootStrapper 实现 ApplicationListener<ContextStartedEvent> {
【发布时间】:2013-03-07 12:15:43
【问题描述】:

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

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

我错过了什么吗?

【问题讨论】:

  • 默认范围是单例
  • 你的问题是什么? “但它不起作用”不是对任何(未命名)问题的有效描述!
  • 谢谢,更新了问题。
  • 如何检查它是否创建了 bean 的多个实例?
  • 你把断点放在哪里,在构造函数中?

标签: spring web-applications


【解决方案1】:

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

@Component
public class BootStrapper() {

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

【讨论】:

  • 您可能指的是 javax.annotation.PostConstruct(不是 PostCreate)。此外,应将返回类型添加到“doSomething”方法中。
【解决方案2】:

试试这样:

@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);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多