2012-04-12 36 views
2

我正在使用Spring MVC 3.05。Java EE和Spring MVC“bootstrap”/服务器启动时的运行代码

我想知道什么是创建引导类的最佳方式是?想想Grails吧。 在以前的项目,我相信另一个人宣布一个Spring bean和schedueler,但我还记得那是一个有点难看:

<bean id="bootstrap" class="com.jobs.Bootstrap" /> 

<task:scheduler id="SpringScheduele" /> 
<task:scheduled-tasks scheduler="SpringScheduele"> 
<task:scheduled ref="bootstrap" method="onServerStart" fixed-delay="5000000000"/
</task:scheduled-tasks> 

我相信,这将使其火启动,然后等待那个时候直到它触发再次。不是很理想。

public class Bootstrap { 

    public void onServerStart() { 
     System.out.println("....");   
    }  
} 

有没有更好的方法来做到这一点?

回答

2

您必须创建一个bean实现ApplicationListener,听ContextRefreshedEvent

@Component 
public class Bootstrap implements ApplicationListener<ContextRefreshedEvent> { 
    @Override 
    void onApplicationEvent(ContextRefreshedEvent event) 
     ... 
    }  
} 
+1

如果你想要确保所有的bean都是在引导之前创建并初始化的,那么这就是要走的路。 – sourcedelica 2012-04-13 03:27:56

+0

谢谢。我猜测当时所有的EJB和数据库都会被加载? – momomo 2012-04-13 11:44:02

+0

应该不是ApplicationContextEvent而不是刷新的?我只是想让它在启动时运行一次,我猜测另一个会在代码更改后运行它,然后发布.. – momomo 2012-04-13 11:48:13

1

我想你可以创建一个类,实现InitializingBean,例如,是这样的:

public class Bootstrap implements InitializingBean { 
    @Value("${my.prop.value}") 
    Integer somePropValue; 

    @Overrides 
    public void afterPropertiesSet() { 
     // runs after constructor & setter injection 
    } 
} 
+0

我只是去尝试完全一样的例子。但是这种方法似乎并不火。我需要做其他事吗?去豆子?我在xml配置文件中注释驱动... – momomo 2012-04-12 13:56:32

+1

将@Component添加到类中,以便组件扫描将实例化bean。 – Kevin 2012-04-12 15:43:55