【问题标题】:Is there a spring equivalent to @Startup?是否有相当于@Startup 的弹簧?
【发布时间】:2014-02-06 10:25:38
【问题描述】:

我必须将企业应用程序转换为 Spring。到目前为止,我一切正常。但我仍然需要替换我的 2 个 bean 上的 @Startup 注释。

有没有相当于春天的东西,或者你会在春天怎么做?

提前致谢!

【问题讨论】:

  • 你能解释一下它的作用吗?
  • @RC。你能解释一下吗?
  • @chrylis 它标记了一个单例 bean (EJB),以便在应用程序启动序列期间进行急切初始化。但是 Spring 会自动启动它的 bean,所以我想知道是否需要它。
  • 不需要。如果 Spring 知道 bean(通过扫描或由于显式声明),它会在上下文初始化期间被初始化。
  • @Startup 表示急切初始化。由于 Java EE 和 spring 中的默认值是相反的(EE 中的非单例惰性和 spring 中的单例渴望),您可以开箱即用。 @Component @Transactional 大致等于 @Singleton @Startup

标签: java tomcat quartz-scheduler


【解决方案1】:

不确定这是否是您要求的。我总是在我的 Spring-beans 中使用 @PostConstruct 注释来做一些需要在应用程序启动时完成的事情:

@Component
public class SchedulerBootstrap {

    @Autowired
    MyRepository myRepository;

    @Autowired
    OpenPropertyPlaceholderConfigurer configurer;

    @PostConstruct
    /**
     * This method will be called after the bean has been 
     * instantiated and all dependencies injected.
     */
    public void init() {

    }
}

添加一个示例,说明如何编写单元测试来试验 bean 在 Spring 上下文中的行为。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

@ContextConfiguration(locations = {"classpath:spring-context.xml"})
public class BootstrapTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    SchedulerBootstrap schedulerBootstrap;

    @Test
    public void myTest() { 
        //Some code that berifies that init-method had been called.
        //Or start unit test in debug-mode and add a breakpoint in the 
        //init-method, you will see it being called before the test is executed.
    }
}

【讨论】:

  • 我有@PostConstruct aswel 并且在想同样的事情。春季可能不需要“@Startup”,因为我相信 bean 在启动时已经初始化。虽然我很想确认一下。
  • 是的,我可以确认它正在工作。当然,您需要首先定义一个初始化 bean 的 spring-context。请查看我添加的关于如何编写单元测试来确认行为的示例。
  • 抱歉,但 JEE '@Startup' 注释是关于启动相互依赖的组件之间的优先级......'@PostConstruct' 不能保证在启动另一个组件时创建并准备好所需的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2017-01-08
  • 2010-10-16
  • 2023-04-04
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多