我以为我设置了一个 spring bean,以便当我的 Web 应用程序上下文初始化时,start 方法会运行,但它没有运行。当我在 Debug模式下启动应用程序时,我从未在启动方法中遇到断点。这是我设置类(class)的方式:
@Transactional
@Service
public class ServerStartup implements Lifecycle {
@Autowired
private EmpireService es;
/**
* sets up the server the first time. Should only be called once
*/
private boolean setup() {
[... sets stuff up, saves the empire]
}
/**
* initializes the Empire with its necessary value
*/
@Override
public void start() {
Empire empire = es.getEmpire();
if (empire == null) {
//initialize all data as there is no "empire"
this.setup();
empire = es.getEmpire();
}
Empire.setEmpireGold(empire.getInstanceEmpireGold());
}
/**
* does nothing
*/
@Override
public void stop() {
}
/**
* does nothing
*/
@Override
public boolean isRunning() {
return false;
}
}
我需要这样做的原因是当我的程序启动时,它需要检查 map 是否已经构建。如果还没有,就需要 build 一个。此外,它本质上是设置一个缓存值,即帝国的 EmpireGold。
如果有比实现生命周期更好、更有效的方法来做到这一点,我愿意接受建议。否则我只想让它工作!
最佳答案
有不止一种方法可以指示 Spring 在创建 bean 后运行一些初始化逻辑。我个人偏好是使用@PostConstruct
注解,因为它是独立于 Spring 或任何其他容器的标准(在 javax.annotation
包中定义)。
如果您选择此解决方案并注释您的 start()
方法 @PostConstruct
,不要忘记包含 <context:annotation-config/>
在您的配置中,否则它将被忽略。
请参阅有关此注释的 Spring 文档 here .
对于同一问题的替代解决方案,请查看 "Customizing the nature of a bean" 部分。 .
关于java - Spring生命周期启动方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328249/