1

我编写休眠+弹簧应用程序。

应用程序启动后(但在第一次使用之前)我想检查数据库状态。

如果状态良好 - 跳过逻辑

如果状态不好 - 执行使状态良好的逻辑。

你能猜出这个问题的最佳实践吗?

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 次以上。

我希望它只调用一次

4

3 回答 3

2

我会使用(假设你在 servlet 上下文环境中)监听器,我会通过实现创建一个监听器javax.servlet.ServletContextListener并将它们作为最后一个监听器。它将被称为最后一个侦听器(也取决于服务器,请检查服务器的文档)。在听众中,我会确保状态良好。好消息是,它在对服务器的任何请求之前被调用。Web 服务器/Web 容器为您保证这一点。

例子:

public class MyContextListener implements ServletContextListener {
      public void contextInitialized(ServletContextEvent sce){
          //do your work here
      }     
}

在网络 xml 中:

<listener>
        <listener-class>com.my.MyContextListener</listener-class>
</listener>
于 2013-10-21T14:00:36.640 回答
1

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

于 2013-10-21T13:39:12.257 回答
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调用两次,因为可能有两个不同的上下文初始化事件。即使您没有contextConfigLocation为 DispatcherServlet 指定 a 它仍然会创建一个子上下文,并且第二个刷新事件是针对该上下文的。您可以使用

event.getApplicationContext()

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

于 2013-10-21T14:23:42.733 回答