java - 无法注册 MBean [HikariDataSource (testdb)]

标签 java spring spring-data-jpa hikaricp junit5

我想在新项目中使用 Spring Data JPA。我基本上遵循https://spring.io/guides/gs/accessing-data-jpa/中描述的设置.

当我启动应用程序或开始单个测试时,一切正常。

一旦我同时开始两个测试,Spring 就无法在第二个测试中加载 ApplicationContext,因为它失败了:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [HikariDataSource (testdb)] with key 'dataSource'; nested exception is javax.management.InstanceAlreadyExistsException: com.zaxxer.hikari:name=dataSource,type=HikariDataSource

如何避免第二次尝试注册 HikariDataSource?

这是我的 build.gradle

dependencies {
    compileOnly "org.projectlombok:lombok:1.16.12"

    compile "org.springframework.boot:spring-boot-starter-web"
    compile "org.springframework.boot:spring-boot-starter-data-jpa"

    compile "com.h2database:h2"

    compile "org.apache.commons:commons-lang3:3.6"

    testCompile "org.junit.jupiter:junit-jupiter-api:5.0.0"
    testCompile "org.junit.jupiter:junit-jupiter-params:5.0.0"

    testRuntime "org.junit.platform:junit-platform-launcher:1.0.0"
    testRuntime "org.junit.jupiter:junit-jupiter-engine:5.0.0"

    testCompile "org.springframework.boot:spring-boot-starter-test"
}

和第一个测试类

@SpringJUnitConfig(Application.class)
class FirstRepositoryTest {
    @Autowired
    private FirstRepository firstRepository;

使用junit 4和@RunWith(SpringJUnit4ClassRunner.class)解决了问题,所以肯定是junit 5和spring交互导致的。

最佳答案

您需要为所有测试加载一次 Spring Context,例如 post它使用@ContextConfiguration:

that problem was loading the Spring Context with each test class. The solution was restructuring the test classes by extending an AbstractContext base class which loaded a Spring Context for all tests to share, and all the Beans therein.

关于java - 无法注册 MBean [HikariDataSource (testdb)],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546647/

相关文章:

java - 菜单程序中的可变错误

java - 从SecurityContextHolder获取电子邮件地址 spring java MVC

java - Spring Data JPA 难以理解的工作逻辑

使用内连接 hibernate 单向@OneToOne

java - 彻底销毁 Spring Application Context

java - SSLHandshakeException - java.security.cert.CertPathValidatorException : non-null policy tree required and policy tree is null

java - HTML 和 Java 初学者网站创建

java - 当远程套接字的设备关闭或应用程序强制关闭时,如何理解 java 远程套接字无法访问

java - org.springframework.jms.support.converter.MappingJackson2MessageConverter 线程安全吗?

java - Maven:缺少 Artifact org.springframework:spring:jar:4.2.6