Spring 会话 JDBC 在我的项目中添加问题

Spring Session JDBC Problem adding in my project

目前我有一个带有 Spring MVC 的项目,它已经与数据库 (MariaDB) 交互,我想尝试 spring-session-jdbc。我在这个 spring-session 中找到了文档,我按照文档中的说明进行操作,但是当我在 Tomcat 中部署它时应用程序没有启动。 Tomcat 中的日志不是很有帮助。这是我的代码:

@Configuration
@PropertySource("classpath:application.properties")
@EnableTransactionManagement
@EnableJdbcHttpSession
@ComponentScans(value = {@ComponentScan("com.havistudio.web.testapp.dao"), @ComponentScan("com.havistudio.web.testapp.service")})
public class AppConfig {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.havistudio.web.testapp.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        dataSource.setConnectionTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.connection-timeout")));
        dataSource.setMinimumIdle(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.minimum-idle")));
        dataSource.setMaximumPoolSize(Integer.parseInt(environment.getRequiredProperty("spring.datasource.hikari.maximum-pool-size")));
        dataSource.setIdleTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.idle-timeout")));
        dataSource.setMaxLifetime(Long.parseLong(environment.getRequiredProperty("spring.datasource.hikari.max-lifetime")));
        dataSource.setAutoCommit(Boolean.parseBoolean(environment.getRequiredProperty("spring.datasource.hikari.auto-commit")));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }

    @Bean
    public JavaMailSender getMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        //Using gmail
        mailSender.setHost("mail.test.com");
        mailSender.setPort(587);
mailSender.setUsername("info@test.com");
        mailSender.setPassword("dsffsdfsdfsd");

        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.smtp.auth", "true");
        javaMailProperties.put("mail.smtp.starttls.enable", "true");
        javaMailProperties.put("mail.smtp.ssl.trust", "mail.test.com");
        //javaMailProperties.put("mail.debug", "true");//Prints out everything on screen

        mailSender.setJavaMailProperties(javaMailProperties);
        return mailSender;
    }
}

我的初始化程序:

public class MyInitializer extends AbstractHttpSessionApplicationInitializer {

    public MyInitializer() {
        super(AppConfig.class);
    }

}

我的application.properties

spring.session.store-type=jdbc

pom.xml

 <!-- Spring Session JDBC -->
 <dependency>
     <groupId>org.springframework.session</groupId>
     <artifactId>spring-session-jdbc</artifactId>
     <version>2.5.1</version>
  </dependency>

我的日志:

 21-Aug-2021 18:23:45.336 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/TzokerStatisticsApp]
21-Aug-2021 18:23:45.694 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war]
2021-08-21 18:23:50,242 localhost-startStop-3 DEBUG Apache Log4j Core 2.14.1 initializing configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,246 localhost-startStop-3 DEBUG Installed 1 script engine
Warning: Nashorn engine is planned to be removed from a future JDK release
2021-08-21 18:23:50,252 localhost-startStop-3 DEBUG Oracle Nashorn version: 11.0.11, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Core' found 122 plugins
2021-08-21 18:23:50,253 localhost-startStop-3 DEBUG PluginManager 'Level' found 0 plugins
2021-08-21 18:23:50,257 localhost-startStop-3 DEBUG PluginManager 'Lookup' found 16 plugins
2021-08-21 18:23:50,260 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,273 localhost-startStop-3 DEBUG PluginManager 'TypeConverter' found 26 plugins
2021-08-21 18:23:50,282 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,283 localhost-startStop-3 DEBUG PluginManager 'Converter' found 44 plugins
2021-08-21 18:23:50,284 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2021-08-21 18:23:50,294 localhost-startStop-3 DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n), name="LogToConsole", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2021-08-21 18:23:50,296 localhost-startStop-3 DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2021-08-21 18:23:50,297 localhost-startStop-3 DEBUG PatternLayout$Builder(pattern="%d %p %c{1.} [%t] %m%n", PatternSelector=null, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2021-08-21 18:23:50,323 localhost-startStop-3 DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG TimeBasedTriggeringPolicy$Builder(interval="null", modulate="null", maxRandomDelay="null")
2021-08-21 18:23:50,327 localhost-startStop-3 DEBUG Building Plugin[name=SizeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy].
2021-08-21 18:23:50,333 localhost-startStop-3 DEBUG createPolicy(size="1 MB")
2021-08-21 18:23:50,335 localhost-startStop-3 DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)})
2021-08-21 18:23:50,336 localhost-startStop-3 DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2021-08-21 18:23:50,339 localhost-startStop-3 DEBUG DefaultRolloverStrategy$Builder(max="10", min="null", fileIndex="null", compressionLevel="null", ={}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml))
2021-08-21 18:23:50,341 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender].
2021-08-21 18:23:50,344 localhost-startStop-3 DEBUG RollingRandomAccessFileAppender$Builder(fileName="logs/TzokerStatisticsApp/app.log", filePattern="logs/TzokerStatisticsApp/${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz", append="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=10, useMax=true)), advertise="null", advertiseURI="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d %p %c{1.} [%t] %m%n), name="LogToRollingRandomAccessFile", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null, ={})
2021-08-21 18:23:50,354 localhost-startStop-3 DEBUG Starting RollingRandomAccessFileManager logs/TzokerStatisticsApp/app.log
2021-08-21 18:23:50,357 localhost-startStop-3 DEBUG PluginManager 'FileConverter' found 2 plugins
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Setting prev file time to 2021-08-16T19:38:00.766+0300
2021-08-21 18:23:50,365 localhost-startStop-3 DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false), SizeBasedTriggeringPolicy(size=1048576)])
2021-08-21 18:23:50,366 localhost-startStop-3 DEBUG Initializing triggering policy TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Initializing triggering policy SizeBasedTriggeringPolicy(size=1048576)
2021-08-21 18:23:50,367 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToRollingRandomAccessFile", level="null", Filter=null)
2021-08-21 18:23:50,368 localhost-startStop-3 DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.AsyncAppender].
2021-08-21 18:23:50,370 localhost-startStop-3 DEBUG AsyncAppender$Builder(={LogToRollingRandomAccessFile}, errorRef="null", blocking="null", shutdownTimeout="null", bufferSize="null", name="Async", includeLocation="null", Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), ignoreExceptions="null", BlockingQueueFactory=null, Filter=null, ={})
2021-08-21 18:23:50,371 localhost-startStop-3 DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2021-08-21 18:23:50,372 localhost-startStop-3 DEBUG createAppenders(={LogToConsole, LogToRollingRandomAccessFile, Async})
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG createAppenderRef(ref="Async", level="null", Filter=null)
2021-08-21 18:23:50,373 localhost-startStop-3 DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2021-08-21 18:23:50,376 localhost-startStop-3 DEBUG createLogger(additivity="false", level="DEBUG", name="com.havistudio.web.testapp", includeLocation="null", ={Async}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2021-08-21 18:23:50,382 localhost-startStop-3 DEBUG createAppenderRef(ref="LogToConsole", level="null", Filter=null)
2021-08-21 18:23:50,383 localhost-startStop-3 DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2021-08-21 18:23:50,384 localhost-startStop-3 DEBUG createLogger(additivity="null", level="ERROR", includeLocation="null", ={LogToConsole}, ={}, Configuration(C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml), Filter=null)
2021-08-21 18:23:50,385 localhost-startStop-3 DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2021-08-21 18:23:50,386 localhost-startStop-3 DEBUG createLoggers(={com.havistudio.web.testapp.root})
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] initialized
2021-08-21 18:23:50,388 localhost-startStop-3 DEBUG Starting configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml]
2021-08-21 18:23:50,395 localhost-startStop-3 DEBUG org.apache.logging.log4j.core.util.SystemClock supports precise timestamps.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Started configuration XmlConfiguration[location=C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml] OK.
2021-08-21 18:23:50,399 localhost-startStop-3 DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG OutputStream closed
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2021-08-21 18:23:50,400 localhost-startStop-3 DEBUG Appender DefaultConsole-1 stopped with status true
2021-08-21 18:23:50,401 localhost-startStop-3 DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration@39d9ebd0 OK
2021-08-21 18:23:50,407 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b
2021-08-21 18:23:50,410 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=StatusLogger
2021-08-21 18:23:50,412 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=ContextSelector
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=
2021-08-21 18:23:50,415 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Loggers,name=com.havistudio.web.testapp
2021-08-21 18:23:50,417 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToRollingRandomAccessFile
2021-08-21 18:23:50,418 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=Appenders,name=LogToConsole
2021-08-21 18:23:50,420 localhost-startStop-3 DEBUG Registering MBean org.apache.logging.log4j2:type=5a383f6b,component=AsyncAppenders,name=Async
2021-08-21 18:23:50,421 localhost-startStop-3 DEBUG Reconfiguration complete for context[name=5a383f6b] at URI C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp\WEB-INF\classes\log4j2.xml (org.apache.logging.log4j.core.LoggerContext@73aa23c5) with optional ClassLoader: null
2021-08-21 18:23:50,423 localhost-startStop-3 DEBUG Shutdown hook enabled. Registering a new one.
2021-08-21 18:23:50,425 localhost-startStop-3 DEBUG LoggerContext[name=5a383f6b, org.apache.logging.log4j.core.LoggerContext@73aa23c5] started OK.
21-Aug-2021 18:23:50.606 INFO [localhost-startStop-3] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Starting...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Start completed.
21-Aug-2021 18:23:51.592 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
21-Aug-2021 18:23:51.593 SEVERE [localhost-startStop-3] org.apache.catalina.core.StandardContext.startInternal Context [/TzokerStatisticsApp] startup failed due to previous errors
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown initiated...
[localhost-startStop-3] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Shutdown completed.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [TzokerStatisticsApp] registered the JDBC driver [org.mariadb.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
21-Aug-2021 18:23:51.624 WARNING [localhost-startStop-3] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [TzokerStatisticsApp] appears to have started a thread named [Log4j2-AsyncAppenderEventDispatcher-1-Async] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.base@11.0.11/jdk.internal.misc.Unsafe.park(Native Method)
 java.base@11.0.11/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
 java.base@11.0.11/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2081)
 java.base@11.0.11/java.util.concurrent.ArrayBlockingQueue.take(ArrayBlockingQueue.java:417)
 org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.dispatchAll(AsyncAppenderEventDispatcher.java:70)
 org.apache.logging.log4j.core.appender.AsyncAppenderEventDispatcher.run(AsyncAppenderEventDispatcher.java:62)
21-Aug-2021 18:23:51.627 INFO [localhost-startStop-3] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:\Users\kostas\apache-tomcat-8.5.41\webapps\TzokerStatisticsApp.war] has finished in [5,933] ms

我确定我在这里遗漏了什么,但我不知道是什么。

终于找到问题所在了!我深入查看了日志文件,特别是 localhost*.log 文件,我发现了这个:

3 Spring WebApplicationInitializers detected on classpath
22-Aug-2021 11:15:52.337 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
22-Aug-2021 11:15:53.251 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
    java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:263)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4768)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:744)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:980)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1851)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)

然后我将我的 MyInitializer class 修改为:

public class MyInitializer extends AbstractHttpSessionApplicationInitializer {


}

它立马奏效了!