Java 冬眠+;春季应用。在使用数据库之前添加逻辑
我编写了hibernate+spring应用程序 在应用程序启动之后(但在第一次使用之前),我想检查数据库状态 如果状态良好-跳过逻辑 若状态是坏的,则执行将使状态为好的逻辑 你能猜出解决这个问题的最佳方法吗 为Debojit Saikia更新 如果我写这段代码:Java 冬眠+;春季应用。在使用数据库之前添加逻辑,java,spring,hibernate,spring-mvc,orm,Java,Spring,Hibernate,Spring Mvc,Orm,我编写了hibernate+spring应用程序 在应用程序启动之后(但在第一次使用之前),我想检查数据库状态 如果状态良好-跳过逻辑 若状态是坏的,则执行将使状态为好的逻辑 你能猜出解决这个问题的最佳方法吗 为Debojit Saikia更新 如果我写这段代码: @Configuration public class UiConfig { @Bean public AppListener getMyListener(){ AppListener appList
@Configuration
public class UiConfig {
@Bean
public AppListener getMyListener(){
AppListener appListener = new AppListener();
System.out.println();
System.out.println();
System.out.println(" appListener method ");
System.out.println();
System.out.println();
return appListener;
}
}
class AppListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println();
System.out.println();
System.out.println(" hello AppListener");
System.out.println();
System.out.println();
}
}
这个监听器在我运行tomcat之后调用了1次以上
我希望它只调用一次您可以在其中一个bean上实现InitializingBean或使用@PostConstruct。创建bean时,这将在带注释(实现)的方法中执行代码。因此,请在这里执行您的逻辑,不要忘记事务。另外,您可能对@DependsOn注释感兴趣(或取决于属性)我将使用(假设您在servlet上下文环境中)侦听器,我将通过实现
javax.servlet.ServletContextListener
创建一个侦听器,并将它们作为最后一个侦听器。它将作为最后一个侦听器调用(也取决于服务器,请检查服务器的文档)。在监听器中,我会确保状态良好。这样做的好处是,它在向服务器发出任何请求之前被调用。Web服务器/Web容器为您提供了这方面的保证
例如:
public class MyContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce){
//do your work here
}
}
在web xml中:
<listener>
<listener-class>com.my.MyContextListener</listener-class>
</listener>
com.my.MyContextListener
您可以使用ApplicationListener
来侦听ContextRefreshedEvent
事件,以便在加载所有bean、检测并激活后处理器bean以及ApplicationContext
对象准备就绪后轮询数据库:
public class AppListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// CODE TO CHECK DB STATE
}
}
要找出执行侦听器的上下文。在web.xml中,我需要编写org.springframework.web.context.ContextLoaderListener,在那里我必须编写我的逻辑?您能提供更多详细信息吗?例如,只需创建带有“@Service”注释的类或带有“@PostConstruct”注释的方法的“@Component”将在应用程序启动时调用一次
public class AppListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// CODE TO CHECK DB STATE
}
}
<bean id="appListener" class="x.y.z.AppListener" />
event.getApplicationContext()