[英]hibernate+spring application. add logic before using database
我寫了hibernate + spring應用程序。
應用程序啟動后(但在第一次使用之前)我想檢查數據庫狀態。
如果狀態良好 - 跳過邏輯
如果狀態不好 - 執行將使狀態良好的邏輯。
你能猜出這個問題的最佳實踐嗎?
Debojit Saikia的 更新
如果我寫這個代碼:
@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();
}
}
我看到下一個登錄控制台:
21.10.2013 18:46:05 org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_37\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.6.0_37\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;%ANT_HOME%/bin;C:\Program Files\Apache Software Foundation\apache-maven-3.0.5\\bin;C:\Program Files\Apache Software Foundation\apache-ant-1.9.0/bin;.
21.10.2013 18:46:06 org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ui' did not find a matching property.
21.10.2013 18:46:06 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
21.10.2013 18:46:06 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
21.10.2013 18:46:06 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 762 ms
...
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/security_config.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@77be91c8: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,candidateDao,eventDaoImpl,eventStatusDao,eventTypeDao,noteDao,skillDao,userDao,vacancyDao,candidateService,eventService,utilService,vacancyService,baseMenuController,candidateMenuController,provider,eventMenuController,homeController,uiConfig,vacancyMenuController,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,dataSource,sessionFactory,entryPoint,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,messageSource,getMyListener]; root of factory hierarchy
appListener method
hello AppListener
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4544 ms
21.10.2013 18:46:21 org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Mon Oct 21 18:46:21 MSK 2013]; parent: Root WebApplicationContext
...
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/addVacancy],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.epam.hhsystem.web.controllers.VacancyMenuController.addVacancy(com.epam.hhsystem.model.vacancy.Vacancy,org.springframework.validation.BindingResult,org.springframework.ui.Model,org.springframework.web.servlet.mvc.support.RedirectAttributes)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
appListener method
hello AppListener
hello AppListener
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 770 ms
21.10.2013 18:46:22 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
21.10.2013 18:46:22 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
21.10.2013 18:46:22 org.apache.catalina.startup.Catalina start
INFO: Server startup in 16053 ms
我運行tomcat后,這個監聽器會調用1次。
我希望它只調用一次
我會使用(假設您在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>
您可以在其中一個bean上實現InitializingBean或使用@PostConstruct。 這將在創建bean時在帶注釋(實現)的方法中執行代碼。 所以你的邏輯在那里,不要忘記交易。 您可能對@DependsOn annotaion(或依賴屬性)感興趣
您可以使用ApplicationListener
監聽ContextRefreshedEvent
事件,以便在加載所有Bean后,可以檢測並激活后處理器bean,並且可以使用ApplicationContext
對象來輪詢數據庫:
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" />
這樣,在初始化或刷新應用程序上下文時,將通知bean。
編輯:
listener
器被調用兩次,因為可能存在兩個不同的上下文初始化事件。 即使您沒有為DispatcherServlet指定contextConfigLocation
,它仍然會創建子上下文,而第二個刷新的事件是針對該上下文的。 您可以使用
event.getApplicationContext()
找出執行偵聽器的上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.