请教在Spring MVC中,如何实现启动时从数据库读取信息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请教在Spring MVC中,如何实现启动时从数据库读取信息相关的知识,希望对你有一定的参考价值。

读db数据的对象,只要被Spring加载了,都会读到ApplicationContext(应用环境)中,

然后任何控制器Controller可以实现ApplicationContextAware(打理应用环境)接口,可以自动加载ApplicationContext,也就可以在控制器的方法中操作其中任一数据对象。

比如某个spring-beans.xml中写上

<bean id="myService" class="com.mypackage.MyDatabaseService" />

然后在控制器中

@Controller
class MyController implements ApplicationContextAware
   public MyDatabaseService service;
   @override public setApplicationContext(ApplicationContext ac)
       service=(MyDatabaseService) ac.getBean("myService");
   

这样就自动加载了

参考技术A   这个挺简单的。
  web.xml中
  <servlet>
  <servlet-name>t1</servlet-name>
  <servlet-class>com.abc.test.T1</servlet-class>
  <load-on-startup>1</load-on-startup>
  </servlet> <load-on-startup>标记web容器是否在启动的时候就加载这个servlet,当值为0或者大于0时,表示web容器在应用启动时就加载这个servlet;

  当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载;

  百度一下,应该挺多的。

  正数的值越小,启动该servlet的优先级越高。本回答被提问者和网友采纳

如何在带有注解配置的spring mvc中使用spring数据

【中文标题】如何在带有注解配置的spring mvc中使用spring数据【英文标题】:How to use spring data in spring mvc with annotation configuration 【发布时间】:2017-07-25 00:39:26 【问题描述】:

我在我的项目中使用带有 spring mvc 的 spring data jpa。尽管如此,我总是得到错误。 如果我评论 JpaConfig.java,我的应用程序运行良好。 我不知道为什么?请你帮帮我:

我的代码:

ConfigInitializer.java

package com.example.system.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class ConfigInitializer implements WebApplicationInitializer 

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    public void onStartup(ServletContext servletContext)
            throws ServletException 
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);

        ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
                new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    

WebAppConfig.java

package com.example.system.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebAppConfig extends WebMvcConfigurerAdapter 

    /**
     * Configure ViewResolvers to deliver preferred views.
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) 

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    
    /**
     * Configure MessageSource to lookup any validation/error message in internationalized property files
     */
    @Bean
    public MessageSource messageSource() 
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    

JpaConfig.java

package com.example.system.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@PropertySource("classpath:db/application.properties")
@EnableTransactionManagement
@EnableJpaRepositories("com.example.repository")
public class JpaConfig 
    private static final String PROPERTY_NAME_DATABASE_DRIVER = "jdbc.driverClassName";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "jdbc.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "jdbc.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "jdbc.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
    @Resource
    private Environment env;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() 
        HikariConfig dataSource = new HikariConfig();
        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
        return new HikariDataSource(dataSource);
    

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
        entityManagerFactoryBean.setJpaProperties(hibProperties());

        return entityManagerFactoryBean;
    

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() 
        return new HibernateJpaVendorAdapter();
    

    private Properties hibProperties() 
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        return properties;
    

    @Bean
    @Autowired
    public JpaTransactionManager transactionManager(EntityManagerFactory emf) 
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    


application.properties

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:db11g
jdbc.username=username
jdbc.password=password

hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-update
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.format_sql=true
entitymanager.packages.to.scan=com.example.entity

User.java

package com.example.entity;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Date;

@Entity
@Table(name = "USER")    
public class User 
    @Id
    @Column(name = "id")
    @SequenceGenerator(name = "seq", sequenceName = "user_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @Getter @Setter
    private long id;

    @Column(name = "userCode", nullable = false, length = 20)
    @Getter @Setter
    private String userCode;

    @Column(name = "name", nullable = false, length = 20)
    @Getter @Setter
    private String name;

UserRepository.java

package com.example.repository;

import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> 
    List<User> findByEmail(String email);

    List<User> findByEmailAndPassword(String email, String password);

UserServiceImpl.java

...
    @Service("userService")
    public class UserServiceImpl implements UserService 
        @Autowired
        private UserRepository userRepository;
    @Transactional(readOnly = true)
        @Override
        public User findUserByEmail(String email) throws ServiceException 
            List<User> users = userRepository.findByEmail(email);
            if (users.size() == 1) 
                return users.get(0);
             else if(!users.isEmpty()) 
                Log.SERVICE_LOG.info("Duplicated email found!!! Email: " + email);
            
            throw new ResourceNotFoundException("Cannot find any user with email: " + email);
        
    
...

错误:

2017 年 3 月 5 日 08:55:44.271 信息 [RMI TCP 连接 (43)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log 1 春天 在类路径上检测到 WebApplicationInitializers 2017 年 3 月 5 日 08:55:44.371 信息 [RMI TCP 连接 (43)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log 初始化 Spring 根 WebApplicationContext 05-Mar-2017 08:55:49.686 严重 [RMI TCP 连接(43)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart 异常 将上下文初始化事件发送到类的侦听器实例 org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“userRepository”的 bean 时出错:不满足的依赖关系 通过构造函数参数0表示;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 'java.lang.Class>' 可用:预计至少有 1 个符合自动装配条件的 bean 候选人。依赖注解: at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) 在 org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742) 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) 在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) 在 org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) 在 org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) 在 org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) 在 org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4725) 在 org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189) 在 org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 在 org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752) 在 org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728) 在 org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) 在 org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:498) 在 org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) 在 com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) 在 com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) 在 org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482) 在 org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:498) 在 org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300) 在 com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) 在 com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) 在 javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468) 在 javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76) 在 javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309) 在 javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401) 在 javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829) 在 sun.reflect.GeneratedMethodAccessor198.invoke(未知来源) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:498) 在 sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346) 在 sun.rmi.transport.Transport$1.run(Transport.java:200) 在 sun.rmi.transport.Transport$1.run(Transport.java:197) 在 java.security.AccessController.doPrivileged(Native Method) 在 sun.rmi.transport.Transport.serviceCall(Transport.java:196) 在 sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568) 在 sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826) 在 sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683) 在 java.security.AccessController.doPrivileged(Native Method) 在 sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 在 java.lang.Thread.run(Thread.java:745) 引起: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 'java.lang.Class>' 可用:预计至少有 1 个符合自动装配条件的 bean 候选人。依赖注解: at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 在 org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835) 在 org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ... 59 更多

【问题讨论】:

【参考方案1】:

您可以尝试将@Repository 添加到您的UserRepository 接口吗?

【讨论】:

我尝试添加注释,但仍然出现错误。 注解@Repository 是不必要的,因为在JpaConfig.java 中我已经声明了@EnableJpaRepositories 您是否也可以在您的 JpaConfig 中添加 @ComponentScan(basePackages = "service_package_path", "repository_package_path") 注释。 @KLHauser:我也试过更新 ComponentScan,还是不行:( 嗯,NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class&gt;' 表示另一个原因。为什么 UserServiceImpl 是缩进的,是在另一个类中吗?【参考方案2】:

您应该在您的 User 类中使用 @Entity 和 @Table 注释。此外,我认为 BaseEntity 是您的实体超类,因此您可以在 Base 实体类中使用 @MappedSuperclass 注释。

【讨论】:

感谢您的回复。我已经添加了这些注释,但错误仍然发生。我更新了我的问题。【参考方案3】:

我不知道为什么,但是当我更改库版本时。有效。 旧库(不起作用):

<properties>
        <spring.version>4.3.6.RELEASE</spring.version>
        <spring.security.version>4.0.4.RELEASE</spring.security.version>
        <spring.data.version>1.11.0.RELEASE</spring.data.version>
        <junit.version>4.12</junit.version>
        <http.client>4.3.3</http.client>
        <servlet-api-version>3.1.0</servlet-api-version>
        <jsp-version>2.1</jsp-version>
        <jstl-version>1.2</jstl-version>
        <java.version>1.8</java.version>
        <log4j.version>1.2.17</log4j.version>
        <mokito-all.version>1.10.19</mokito-all.version>
        <powermock-api.version>1.6.5</powermock-api.version>
        <powermock-junit.version>1.6.5</powermock-junit.version>
        <jackson.version>2.8.6</jackson.version>
        <hibernate.version>5.2.6.Final</hibernate.version>
        <h2.version>1.4.193</h2.version>
    </properties>
    <!-- Specifying the Dependencies -->
    <dependencies>
        <!-- Spring 4 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>$spring.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>$spring.version</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>$spring.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>$spring.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>$spring.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>$spring.version</version>
            <scope>test</scope>
        </dependency>
        <!-- Spring security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>$spring.security.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>$spring.security.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>$spring.security.version</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>$spring.security.version</version>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.4.0</version>
        </dependency>
        <!-- Sping data -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>$spring.data.version</version>
        </dependency>
        <!-- Use Apache HttpClient as HTTP Client -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>$http.client</version>
        </dependency>
        <!--&lt;!&ndash;OracleSQL Connector &ndash;&gt;
        <dependency>
          <groupId>ojdbc</groupId>
          <artifactId>ojdbc</artifactId>
          <version>14</version>
        </dependency>-->

        <!--REST-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>$jackson.version</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>$jackson.version</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>$jackson.version</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0</version>
        </dependency>

        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>$hibernate.version</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <!--<dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>5.3.4.Final</version>
        </dependency>-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>$hibernate.version</version>
        </dependency>

        <!-- Add H2 database support [for running with local profile] -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>$h2.version</version>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.0</version>
        </dependency>

        <!-- Servlet and JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>$servlet-api-version</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>$jsp-version</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSTL dependency -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>$jstl-version</version>
        </dependency>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>$junit.version</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>$mokito-all.version</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>$powermock-api.version</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>$powermock-junit.version</version>
            <scope>test</scope>
        </dependency>

        <!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>$log4j.version</version>
        </dependency>
        <!-- Mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mail</artifactId>
            <version>4.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
            <!--<scope>test</scope> -->
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>0.7.4</version>
        </dependency>

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-xml</artifactId>
            <version>2.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>$spring.version</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

        <!-- LOMBOK-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.12</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.mobile</groupId>
            <artifactId>spring-mobile-device</artifactId>
            <version>1.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>[0.4, 0.5)</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>1.12.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <!--Open ID Library-->
        <!-- https://mvnrepository.com/artifact/org.openid4java/openid4java -->
        <dependency>
            <groupId>org.openid4java</groupId>
            <artifactId>openid4java</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

更新库(工作):

<properties>
    <java.version>1.8</java.version>
    <junit.version>4.11</junit.version>
    <slf4j.version>1.7.5</slf4j.version>
    <logback.version>1.0.13</logback.version>
    <!--<spring.version>4.0.0.RELEASE</spring.version>-->
    <spring.version>4.3.6.RELEASE</spring.version>
    <spring-data-jpa.version>1.10.5.RELEASE</spring-data-jpa.version>
    <spring-security.version>3.2.0.RELEASE</spring-security.version>
    <hibernate.version>4.2.6.Final</hibernate.version>
    <aspectj.version>1.7.2</aspectj.version>
    <mysql.version>5.1.26</mysql.version>
    <jackson-json.version>2.8.6</jackson-json.version>
    <commons-dbcp.version>1.2.2</commons-dbcp.version>
    <commons-lang3.version>3.1</commons-lang3.version>
    <apache.tiles>3.0.7</apache.tiles>
  </properties>

  <!--<build>
    <finalName>$project.artifactId</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>$java.version</source>
          <target>$java.version</target>
        </configuration>
      </plugin>
    </plugins>
  </build>-->

  <dependencies>
    <!-- Logging dependencies -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>$slf4j.version</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>$slf4j.version</version>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>$logback.version</version>
    </dependency>

    <!-- Spring dependencies -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

    <!-- Spring Data JPA dependencies -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>$spring-data-jpa.version</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>$hibernate.version</version>
    </dependency>

    <!-- SpringSecurity dependencies -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-core</artifactId>
      <version>$spring-security.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>$spring-security.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>$spring-security.version</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>$spring-security.version</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>$aspectj.version</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>$aspectj.version</version>
    </dependency>

    <!-- Testing dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>$junit.version</version>
      <scope>test</scope>
    </dependency>

    <!-- DB dependencies -->
<!--
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>$mysql.version</version>
    </dependency>
-->

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>$commons-dbcp.version</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>$jackson-json.version</version>
    </dependency>

    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.3</version>
    </dependency>

    <!-- Web dependencies -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.12</version>
      <scope>provided</scope>
    </dependency>
    <!-- Thumbnail -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.7</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-commons-core</artifactId>
      <version>1.4.0.RELEASE</version>
    </dependency>

    <!--TEST-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>$junit.version</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>$spring.version</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-junit</artifactId>
      <version>2.0.0.0</version>
    </dependency>

    <!--APACHE TILES-->
    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-core</artifactId>
      <version>$apache.tiles</version>
    </dependency>
    <dependency>
      <groupId>org.apache.tiles</groupId>
      <artifactId>tiles-jsp</artifactId>
      <version>$apache.tiles</version>
    </dependency>

    <!--REST SWAGGER-->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.6.1</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.6.1</version>
    </dependency>
  </dependencies>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-framework-bom</artifactId>
        <version>$spring.version</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

【讨论】:

【参考方案4】:

您没有扫描存在实体的包。以下更改应该可以解决问题。

private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "com.example.entity";

【讨论】:

不,它不起作用。其实在问问题之前我也试过你的方法:( @Autowired 在 JpaTransactionManager bean 之上不需要。也不需要事务注释。只是一个疯狂的猜测,检查删除自动装配的注释是否有任何作用。 移除自动连线注解并将方法参数更改为 this-public JpaTransactionManager transactionManager(LocalEntityManagerFactoryBean entityManagerFactory) 不,它仍然不起作用。我不知道为什么,但是当我更改库版本时它运行良好。我的解决方案如下。

以上是关于请教在Spring MVC中,如何实现启动时从数据库读取信息的主要内容,如果未能解决你的问题,请参考以下文章

请教mysql spring mvc +mybatis中批量插入的问题

如何让spring mvc web应用启动时就执行特定处理

如何在android中启动活动时从sqlite数据库中删除所有行(数据)

如何让spring mvc web应用启动时就执行特定处理

Spring MVC DispatcherServlet的启动以及初始化

如何在 Spring MVC 应用程序中启动 ApplicationContext 加载线程?