当前位置: 首页 > 知识库问答 >
问题:

spring boot startup与spring boot JPA Starter的问题

闻安宜
2023-03-14

当我试图用spring-boot-starter-data-jpa启动我的spring boot项目时,我遇到了这个特殊的错误。奇怪的是,我的应用程序会在添加几个存储库和服务之前启动,但我似乎无法缩小为什么spring不能初始化一个在添加之前正在工作的存储库的范围。

以下是相关错误:

11:38:42.313 INFO  org.hibernate.Version.logVersion() @37 [localhost-startStop-1] - HHH000412: Hibernate Core {5.0.11.Final}
11:38:42.316 INFO  org.hibernate.cfg.Environment.<clinit>() @213 [localhost-startStop-1] - HHH000206: hibernate.properties not found 
11:38:42.319 INFO  org.hibernate.cfg.Environment.buildBytecodeProvider() @317 [localhost-startStop-1] - HHH000021: Bytecode provider name : javassist
11:38:42.430 INFO  org.hibernate.annotations.common.Version.<clinit>() @66 [localhost-startStop-1] - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
11:38:43.165 INFO  org.hibernate.dialect.Dialect.<init>() @156 [localhost-startStop-1] - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
11:38:43.583 ERROR org.springframework.boot.context.embedded.tomcat.TomcatStarter.onStartup() @63 [localhost-startStop-1] - Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'emailAuthenticationFilter' defined in class path resource [gg/leet/security/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [gg.leet.security.EmailAuthenticationFilter]: Factory method 'emailAuthenticationFilter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManager' defined in class path resource [gg/leet/security/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emailAuthenticationProvider': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl' defined in file [/Users/andrew/Programs/leet-tournaments/backend/build/classes/main/gg/leet/service/UserServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#76212c93' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#76212c93': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
11:38:43.617 WARN  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext.refresh() @550 [restartedMain] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
11:38:43.631 ERROR org.springframework.boot.SpringApplication.reportFailure() @839 [restartedMain] - Application startup failed

最有趣的是这句话:

11:38:43.583错误org.springframework.boot.context.embedde.Tomcat.tomcatstarter.onstartup()@63[localhost-startStop-1]-启动Tomcat上下文时出错。异常:org.springframework.beans.factory.beancreationexception。消息:创建类路径资源[gg/leet/security/websecurityconfig.class]中定义的名为'email authenticationfilter'的bean时出错:通过工厂方法实例化bean失败;嵌套异常为org.springframework.beans.beanInstantiationException:无法实例化[gg.leet.security.emailauthenticationfilter]:工厂方法'emailauthenticationfilter'引发异常;嵌套异常为org.springframework.beans.factory.beanCreationException:创建类路径资源[gg/leet/security/websecurityconfig.class]中定义的名为“authentication manager”的bean时出错:通过工厂方法实例化bean失败;嵌套异常为org.springframework.beans.beanInstantiationException:无法实例化[org.springframework.security.authentication.authenticationManager]:工厂方法“authentication Manager”引发异常;嵌套异常为org.springframework.beans.factory.unsatisfieddependencyexception:创建名为“email authenticationprovider”的bean时出错:通过字段“user service”表示的不满足依赖项;嵌套异常为org.springframework.beans.factory.unsatisfiedDependencyException:创建文件[/users/andrew/programs/leet-tournaments/backend/build//main/gg/leet/service/userserviceimpl.class]中定义的名为“user serviceimpl”的bean时出错:通过构造函数参数0表示的未满足的依赖项;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“User Repository”的bean时出错:设置bean属性“Entity Manager”时无法创建类型为[org.springframework.orm.jpa.SharedEntityManagerCreator]的内部bean“(内部bean)#76212C93”;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“(内部bean)#76212C93”的bean时出错:设置构造函数参数时无法解析对bean“Entity ManagerFactory”的引用;嵌套异常为org.springframework.beans.factory.beanCreationException:创建类路径资源[org/springframework/boot/autociguration/orm/jpa/hibernatejpaAutociguration.class]中定义的名为“Entity ManagerFactory”的bean时出错:调用init方法失败;嵌套异常为javax.persistence.persistenceException:[persistenceUnit:default]无法构建Hibernate SessionFactory

所以在userServiceImpl的参数0中的冒犯类是userRepository

这就是我的UserRepository的样子:

package gg.leet.repository;

import gg.leet.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
    @Query("select u from User u where u.id = ?1")
    Optional<User> findOneById(Long id);
    User save(User user);
    Optional<User> findOneByUsername(String username);
    List<User> findByEmailContaining(String search);
    List<User> findByFirstNameContaining(String search);
    List<User> findByLastNameContaining(String search);
    List<User> findByUsernameContaining(String search);
    @Query("select u from User u where u.username like ?1 or u.firstName like ?1 or u.lastName like ?1")
    Page<User> findByUsernameOrLastNameOrFirstNameContaining(String search, Pageable pageable);
}

UserService实现:

package gg.leet.service;

import gg.leet.model.User;
import gg.leet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Implementation of the UserService over the mysql repository
 */
@SuppressWarnings("unused")
@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public Optional<User> getByUsername(String username) {
        return this.userRepository.findOneByUsername(username);
    }

    @Override
    public Optional<User> getByEmail(String email) { return this.userRepository.findByEmail(email); }

    @Override
    public Optional<User> getById(Long id) {
        return this.userRepository.findOneById(id);
    }

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public Page<User> findByContaining(String search, Pageable pageable) {
        return this.userRepository.findByUsernameOrLastNameOrFirstNameContaining(search, pageable);
    }
}

没什么特别的,但我不明白为什么我们不能为身份验证过滤器实例化一个bean。这个错误有点一般,所以我不知道应该在哪里找。我尝试在配置类中手动初始化EntityManagerFactorybean,并在@enableJParepositories注释中引用它,但没有成功。有什么建议,我也应该看看哪里来解决这个问题?

-----编辑1-----

下面是我的数据源配置,它非常小,但在过去是有效的:

spring:
  profiles: default
  datasource:
    url: jdbc:mysql://localhost:3306/leettournaments?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto: create-drop


spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 25
    max-idle: 10
  jpa:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect

------编辑2------

@SuppressWarnings("unused")
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=Integer.MAX_VALUE, redisFlushMode=RedisFlushMode.IMMEDIATE)
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final Logger LOGGER = LogManager.getLogger(WebSecurityConfig.class);

    @Value("${gg.leet.debug}")
    private boolean debug;

    /**
     * Establishes role hierarchy for user roles.
     * @return the RoleHierarchy
     */
    @Bean
    public RoleHierarchyImpl roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy(
                "ROLE_SUPER_ADMIN > ROLE_LOCATION_ADMIN " +
                        "ROLE_LOCATION_ADMIN > ROLE_REGULAR_USER ");
        return roleHierarchy;
    }

    @Bean
    public RoleHierarchyVoter roleVoter() {
        return new RoleHierarchyVoter(roleHierarchy());
    }


    @Bean
    HeaderHttpSessionStrategy sessionStrategy() {
        return new HeaderHttpSessionStrategy();
    }


    @Bean
    public AuthenticationProvider emailAuthenticationProvider() {
        return new EmailAuthenticationProvider();
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(
                emailAuthenticationProvider()
        ));
    }

    @Bean
    public AuthenticationSuccess authenticationSuccess() {
        return new AuthenticationSuccess();
    }

    @Bean
    public AuthenticationFailure authenticationFailure() {
        return new AuthenticationFailure();
    }

    @Bean
    public EmailAuthenticationFilter emailAuthenticationFilter() {
        EmailAuthenticationFilter filter = new EmailAuthenticationFilter(new AntPathRequestMatcher("/login-process", "POST"));
        applyFilterAuthRules(filter);
        return filter;
    }

    private void applyFilterAuthRules(AbstractAuthenticationProcessingFilter filter) {
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(authenticationSuccess());
        filter.setAuthenticationFailureHandler(authenticationFailure());
        filter.setAllowSessionCreation(true);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/", "/**/*.css", "/**/*.js", "/index.html", "/ws/**", "/assets/**/*");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if(debug) {
            LOGGER.warn("Allowing preflight options requests to all");
            // For the pre-flight request for options
            http
                    .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "/**")
                    .permitAll();
            // Disable csrf on debug dev
            LOGGER.warn("Allowing no CSRF protection");
            http
                    .csrf()
                    .disable();
        } else {
            http
                    .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        }

        http
                .authorizeRequests()
                .antMatchers( "/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)))
                .invalidateHttpSession(true)
                .permitAll()
                .and()
                .addFilterBefore(emailAuthenticationFilter(), FilterSecurityInterceptor.class);



        http.requestCache().requestCache(new NullRequestCache());
        http.headers().cacheControl();
        http.headers().httpStrictTransportSecurity().disable();
        // .headers().contentSecurityPolicy(
        // .and().antMatcher("/bingo/card").;
    }

    @Bean
    protected BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

------编辑3------

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE'
        // classpath 'org.springframework:springloaded:1.2.6.RELEASE'
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    mavenCentral()
}

idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}

jar {
    baseName = 'leet-tournaments'
    version = '0.1.0'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

configurations {
    dev
    all*.exclude module: 'spring-boot-starter-logging'
}

dependencies {

    // Spring Boot Starter Framework
    compile(
            [group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.3.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-starter-log4j2', version: '1.2.0.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '1.4.3.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.3.2.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '1.0.0.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '1.4.3.RELEASE'],
            [group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '1.4.3.RELEASE'],
            [group: 'org.springframework.session', name: 'spring-session', version: '1.3.0.RELEASE'],
            [group: 'org.springframework', name: 'spring-messaging', version: '4.3.6.RELEASE'],
    )

    compile(
            [group: 'javax.mail', name: 'mail', version: '1.4.7'],
            [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.5'],
            [group: 'mysql', name: 'mysql-connector-java', version: '5.1.35'],
            [group: 'org.projectlombok', name: 'lombok', version: '1.16.12'],
            [group: 'com.goebl', name: 'david-webb', version: '1.3.0'],
            [group: 'com.amazonaws', name: 'aws-java-sdk', version: '1.11.77'],
            [group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5', version: '2.8.8'],
            [group: 'com.google.guava', name: 'guava', version: '22.0-rc1'],
    )

    compile(
            [group: 'io.netty',                 name: 'netty-all',              version: '4.1.7.Final'],
            [group: 'io.projectreactor',        name: 'reactor-core',           version: '2.0.7.RELEASE'],
            [group: 'io.projectreactor',        name: 'reactor-net',            version: '2.0.7.RELEASE'],
            [group: 'io.projectreactor.spring', name: 'reactor-spring-core',    version: '2.0.7.RELEASE'],
            [group: 'io.projectreactor.spring', name: 'reactor-spring-context', version: '2.0.7.RELEASE'],
    )

    // testing
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('junit:junit')
}

// gradle wrapper
task wrapper(type: Wrapper) {
    gradleVersion = '3.0'
}

// run spring boot app
bootRun {
    addResources = true
    classpath = sourceSets.main.runtimeClasspath + configurations.dev
}

主类:

@SpringBootApplication
@EnableConfigurationProperties
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan
public class LeetTournaments {
    private static final Logger LOGGER = LogManager.getLogger(LeetTournaments.class);

    public static void main(String[] args) {
        SpringApplication.run(LeetTournaments.class, args);
        // LeetTournaments.initDB();
    }

    static void initDB() {
        Webb webb = Webb.create();
        webb.get("http://127.0.0.1:8080/init").asString();
    }
}

共有1个答案

龙新荣
2023-03-14

null

spring数据存储库通常扩展自repositorycrudrepository接口。如果您使用的是自动配置,那么将从包含主配置类(用@enableAutoConfiguration@springbootapplication注释的类)的包中向下搜索存储库。

-spring boot参考指南,29.3.2 Spring Data JPA储存库。

实际上,我认为这是问题的解决方案(用粗体字体标记的文本):

默认情况下,spring boot将启用JPA存储库支持,并查看@springbootapplication所在的包(及其子包)。如果您的配置的JPA存储库接口定义位于不可见的包中,则可以使用@enablejparepositories及其类型安全basePackageClasses=myRepository.class参数指出备用包。

-入门·使用JPA访问数据。

总之,请考虑更新LeetTournaments类的实现,如下所示:

@EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class LeetTournaments {
    ...
}

希望这有帮助。

 类似资料:
  • 我试图通过Weblogic上的JaCoCo找到代码覆盖率(不是测试用例) 下面是我在服务器下给出的条目- -Java agent:/apps/dev 4/deploy/code-coverage/jaco agent . jar = dest file =/apps/dev 4/deploy/code-coverage/jaco co . exec,append=false,includes=*

  • 我试图用CCSequence制作一个精灵的动画,我需要把参数传递给回调函数,但当我这么做的时候,我得到了 信号11(SIGSEGV),代码1(SEGV_MAPERR),故障地址000000 21 这是我的代码: 我在没有参数的情况下尝试了相同的代码,它很有效。 我正在使用eclipse和调试器没有太大帮助,或者至少我不知道如何,和adb logcat显示: 建立指纹: /espressowifix

  • 问题内容: 我不明白注释和之间的实际区别是什么? 扩展名还是它们具有完全不同的含义?什么时候应该使用它们?在服务层中使用Spring ,在DAO 中使用javax? 谢谢回答。 问题答案: 几年前,Spring定义了自己的Transactional注释以使Spring bean方法具有事务性。 Java EE 7终于做了同样的事情,现在除了EJB方法外,还允许CDI bean方法是事务性的。因此,

  • 我试图创建和预加载嵌入式H2 Db与一些数据使用schema.sql.但一旦我尝试使用POST请求添加新用户,发生以下错误。 2022-07-04 23:35:53.153 错误 8180 --- [NIO-8080-exec-2] O.A.C.C.C.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcher

  • 我们有一个在Jboss AS7.1.1中运行的旧Java应用程序。当前,这个应用程序正在AWS EC2实例类型T3.Medium上运行,该实例类型为2个CPU内核和4GB内存。 我们正在尝试用CI/CD和AWS Fargate使我们的应用程序现代化。我们成功地实现了现代化,但不是靠业绩。 Fargate的任务定义具有与EC2实例相同的CPU和内存(2048 CPU和4096内存)。Farget与E

  • 问题内容: 我正在尝试对我们的客户代码进行基准测试。因此,我决定编写一个多线程程序来对我的客户端代码进行基准测试。我正在尝试测量下面的方法需要多少? 因此,下面是我编写的用于对上述方法进行基准测试的多线程代码。在两种情况下,我看到了很多变化- 1)首先,使用和来处理多线程代码。我得到95%的。我正在使用- 2)但是,如果我运行相同的程序以使用- 代替 当我使用运行代码时,我得到95%,比上面的数字

  • 本文向大家介绍CodeIgniter与PHP5.6的兼容问题,包括了CodeIgniter与PHP5.6的兼容问题的使用技巧和注意事项,需要的朋友参考一下 错误提示: 原代码: 修改后: 以上所述就是本文的全部内容了,希望大家能够喜欢。

  • 响应消息:java.sql.SQLException:无法创建PoolableConnectionFactory(ORA-00604:递归SQL级别1 ORA-12705发生错误:无法访问NLS数据文件或指定的无效环境)