- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尝试使用 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 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
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);
}
用户服务实现:
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。该错误有些笼统,所以我不知道应该在哪里寻找。我试图在配置类中手动初始化 entityManagerFactory
bean 并在 @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();
}
}
最佳答案
请注意标有粗体的文字:
Spring Data repositories usually extend from the
Repository
orCrudRepository
interfaces. If you are using auto-configuration, repositories will be searched from the package containing your main configuration class (the one annotated with@EnableAutoConfiguration
or@SpringBootApplication
) down.— Spring Boot Reference Guide, 29.3.2 Spring Data JPA Repositories.
其实,我认为这是解决问题的方法(粗体标出的文字):
By default, Spring Boot will enable JPA repository support and look in the package (and its subpackages) where
@SpringBootApplication
is located. If your configuration has JPA repository interface definitions located in a package not visible, you can point out alternate packages using@EnableJpaRepositories
and its type-safebasePackageClasses=MyRepository.class
parameter.
总而言之,考虑如下更新 LeetTournaments
类的实现:
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class LeetTournaments {
...
}
希望这对您有所帮助。
关于java - Spring Boot JPA Starter 的 Spring Boot 启动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45611767/
有人可以解释一下 spring-boot-parent 和 spring-boot-starter-parent 之间的区别吗,正如我在下面附加的 GIT HUB 代码链接之一中看到的,他们为 spr
我有与 jersey 框架集成的 Spring Boot 应用程序。 现在,当我尝试运行该应用程序时,它只是停留在 Spring 启动徽标上,之后没有任何 react 。 我也尝试添加 -X ,但徽标
我指的是 Spring Boot 关于 的文档自动配置 和 执行器 模块: 自动配置: Spring Boot AutoConfiguration attempts to automatically
我正在尝试将 apache log4j 集成到我的 Spring boot 应用程序中。这是我的 build.gradle 文件: build.gradle buildscript { rep
使用 Spring Boot Maven 插件的以下命令在生产中启动 Spring Boot 应用程序是否是一个好主意或实践? mvn spring-boot:run 最佳答案 不,这是个坏主意。 您
据我所知,spring boot 和 spring session 为我们提供了一站式自动配置,但是当我的应用程序使用 session redis 和应用程序缓存 redis 时,不是同一个 redi
我希望使用Spring Boot创建一个新的Web应用程序。不幸的是,我的服务器在技术堆栈方面相当有限。它安装了Java 5。 谁能告诉我spring boot是否可以在Java 1.5上运行以及什么
我有3个实体 CarWash(设置Wash) Wash(car_wash_id FK到CarWash) WashComment(wash_id FK到Wash) 有什么办法可以写这个查询 @Qu
我一直在关注this文章。 我正在尝试在Spring-boot应用程序中优雅地处理gRPC错误,的主要目标是能够在gRPC客户端中获取错误状态。 在上面的文章之后,我坚持为异常添加拦截器。如何在Spr
我有一个要使用的自定义log4j布局插件。在IntelliJ中运行或与./gradlew bootRun一起运行时,插件可以正常工作。不使用./gradlew bootJar构建启动jar。 启用-D
我想在给定范围 (5001-5100) 的随机端口上启动 Spring Cloud 应用程序(Spring Boot 1.5.14,Spring Cloud Edgware.SR4)。我知道我们可以使
任何人都可以向我展示或指出不使用 spring boot gradle 插件的 spring boot gradle 项目。 我正在寻找类似不使用 gradle 插件的 spring boot sta
我当时尝试包含上述依赖项之一,但找不到任何区别: spring boot starter web:我可以看到 Flux 和 Mono 类并制作一个响应式(Reactive)休息 Controller
我们一直在为我们的应用程序使用 Springboot 1.X。 现在准备开始一些新的应用程序,想知道我们是应该使用 SpringBoot2.0 还是坚持使用 SpringBoot 1.X? 对一种方式
我希望记录应用程序正在加载 application-profile.propeties 或 application.yml。怎么做。在哪种方法中,我可以听取它并检测它是成功加载还是失败。 最佳答案 您
当我在 pom.xml 中添加简单的 spring-boot-starter-data-jpa 依赖项时,在 pom.xml 文件中出现错误。如果我删除该依赖项,则不会再有错误。我不确定为什么会发生这
我希望记录应用程序正在加载 application-profile.propeties 或 application.yml。怎么做。在哪种方法中,我可以听取它并检测它是成功加载还是失败。 最佳答案 您
我在网上看了很多关于 spring-boot-devtools 的文章和问题,但仍然无法弄清楚为什么它对我不起作用。每次运行我的应用程序时,我都会得到以下信息: 17:54:28.057 [main]
我正在尝试将现有的 Spring 应用程序移植到 Spring Boot。我不使用 spring-boot-starter-data-solr 启动器,但是我的类路径上有 apache solrj (
(这主要是一个历史问题。Pivotal 建议所有论坛讨论都在 StackOverflow 上进行,这就是我在这里问它的原因。) Spring Boot 项目用来证明将应用程序的类和依赖项从可执行 ja
我是一名优秀的程序员,十分优秀!