hibernate + spring应用程序。在使用数据库之前添加逻辑

时间:2013-10-21 13:31:35

标签: java spring hibernate spring-mvc orm

我写了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次。

我希望它只调用一次

3 个答案:

答案 0 :(得分:2)

我会使用(假设您在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>

答案 1 :(得分:1)

您可以在其中一个bean上实现InitializingBean或使用@PostConstruct。这将在创建bean时在带注释(实现)的方法中执行代码。那么你的逻辑在那里,不要忘记交易。您可能对@DependsOn annotaion(或依赖属性)

感兴趣

答案 2 :(得分:0)

您可以使用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()

找出执行侦听器的上下文。