2013-03-10 46 views
1

我以为我设置了一个spring bean,这样当我的web应用程序上下文被初始化时,start方法就会运行,但它不会运行。当我在调试模式下启动我的应用程序时,我从来不会在启动方法中触发断点。以下是我已经班级设置:春季生命周期开始方法不起作用

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

,我需要做的原因是,当我的程序启动时,它需要检查,如果地图已经建成。如果没有,它需要建立一个。此外,它本质上是建立一个缓存的价值,即帝国的帝国黄金。

如果有比实施生命周期更好,更有效的方法,我会接受建议。否则,我只是想要这个工作!

回答

3

有多种方式指示Spring在创建bean后运行一些初始化逻辑。我个人偏好使用@PostConstruct注释,因为它是独立于Spring或任何其他容器的标准(在javax.annotation包中定义)。

如果您选择此解决方案并使用@PostConstruct注释您的start()方法,请不要忘记在您的配置中包含<context:annotation-config/>,否则它将被忽略。

查看Spring注意事项文档here
有关同一问题的替代解决方案,请查看"Customizing the nature of a bean"上的部分。

+0

酷,像魅力一样工作。 – CorayThan 2013-03-10 22:57:03

2

注释你的启动方法@PostConstruct