英文:
I am getting "Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled." Solution for this?
问题
以下是您提供的内容的翻译:
我的文件夹结构:
My Console:
. ____ _ __ _ _
/\ / 大块文本'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | 大块文本'_ | 大块文本'| | 大块文本'_ \/ _` | \ \ \ \
\/ 大块文本)| 大块文本'| | 大块文本'| | 大块文本'|| (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-09 18:04:58.332 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : Starting ProjectApiApplication on LAPTOP-I4F37P4O with PID 16828 (C:\Users\mitad\Documents\STS_Workspace\ProjectAPI\target\classes started by mitad in C:\Users\mitad\Documents\STS_Workspace\ProjectAPI)
2020-08-09 18:04:58.334 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : No active profile set, falling back to default profiles: default
2020-08-09 18:04:58.866 INFO 16828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-09 18:04:58.872 INFO 16828 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-09 18:04:58.872 INFO 16828 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-09 18:04:58.928 INFO 16828 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-09 18:04:58.928 INFO 16828 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 566 ms
2020-08-09 18:04:59.039 INFO 16828 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-09 18:04:59.148 INFO 16828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-09 18:04:59.155 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : Started ProjectApiApplication in 1.04 seconds (JVM running for 1.534)
2020-08-09 18:04:59.231 WARN 16828 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
2020-08-09 18:04:59.233 INFO 16828 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-09 18:04:59.245 ERROR 16828 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at com.api.main.ProjectApiApplication.main(ProjectApiApplication.java:26) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.8.RELEASE.jar:5
<details>
<summary>英文:</summary>
[My folder structure][1]
[1]: https://i.stack.imgur.com/avp85.png
My Console:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-09 18:04:58.332 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : Starting ProjectApiApplication on LAPTOP-I4F37P4O with PID 16828 (C:\Users\mitad\Documents\STS_Workspace\ProjectAPI\target\classes started by mitad in C:\Users\mitad\Documents\STS_Workspace\ProjectAPI)
2020-08-09 18:04:58.334 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : No active profile set, falling back to default profiles: default
2020-08-09 18:04:58.866 INFO 16828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-09 18:04:58.872 INFO 16828 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-09 18:04:58.872 INFO 16828 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-09 18:04:58.928 INFO 16828 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-09 18:04:58.928 INFO 16828 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 566 ms
2020-08-09 18:04:59.039 INFO 16828 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-09 18:04:59.148 INFO 16828 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-09 18:04:59.155 INFO 16828 --- [ main] com.api.main.ProjectApiApplication : Started ProjectApiApplication in 1.04 seconds (JVM running for 1.534)
2020-08-09 18:04:59.231 WARN 16828 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
2020-08-09 18:04:59.233 INFO 16828 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-09 18:04:59.245 ERROR 16828 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at com.api.main.ProjectApiApplication.main(ProjectApiApplication.java:26) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.api.main.ProjectApiApplication.run(ProjectApiApplication.java:19) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
... 5 common frames omitted
Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437) ~[na:1.8.0_202]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898) ~[na:1.8.0_202]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966) ~[na:1.8.0_202]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900) ~[na:1.8.0_202]
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324) ~[na:1.8.0_202]
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522) ~[na:1.8.0_202]
at org.springframework.boot.admin.SpringApplicationAdminMXBeanRegistrar.afterPropertiesSet(SpringApplicationAdminMXBeanRegistrar.java:129) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 17 common frames omitted
2020-08-09 18:04:59.362 INFO 16828 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
ConnectToDatabaseImpl:
package com.api.databse.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service("connectTodb")
public class ConnectToDatabaseImpl implements ConnectToDatabase{
@Value("${jdbc.username:default}")
private String userName;
@Value("${jdbc.password:default}")
private String password;
@Autowired
private Environment environment;
@Override
public void getDatabseDetails() {
try{
Class.forName(environment.getProperty("jdbc.driverClassName"));
Connection connection = DriverManager.getConnection(
environment.getProperty("jdbc.url"),userName,password);
Statement stmt=connection.createStatement();
ResultSet resultSet = stmt.executeQuery(environment.getProperty("jdbc.SQLQuery"));
while(resultSet.next())
System.out.println(resultSet.getInt(1)+" "+resultSet.getString(2)+" "+resultSet.getString(3));
connection.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(ClassNotFoundException ce) {
ce.printStackTrace();
}
}
}
AppConfig:
package com.api.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@ComponentScan(basePackages="com.api")
@PropertySource(value= {"classpath:application.properties"})
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
ProjectApiApplication:
package com.api.main;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.api.configuration.AppConfig;
import com.api.databse.service.ConnectToDatabase;
@SpringBootApplication
@EnableAutoConfiguration
public class ProjectApiApplication implements CommandLineRunner{
@Override
public void run(String...args) throws Exception{
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
ConnectToDatabase connection = (ConnectToDatabase)context.getBean("connectTodb");
connection.getDatabseDetails();
context.close();
}
public static void main(String[] args) {
SpringApplication.run(ProjectApiApplication.class, args);
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ProjectAPI</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ProjectAPI</name>
<description>Project for Spring Boot and API Calling</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</details>
# 答案1
**得分**: 2
删除`spring-context`依赖 - 你已经有了Spring Boot的父级依赖,一般情况下不要引入不同版本的Spring依赖。
**重要提示:** 不要在实现CommandLineRunner接口的类内部运行Spring Boot的主程序。通常,将所有相关代码从`run`方法中提取出来,然后在主程序中使用它,然后移除对CommandLineRunner的实现,以确保一切正常运行。
此外,你不需要使用`EnableAutoConfiguration`注解,因为`@SpringBootApplication`注解已经包含了它。
你也不需要使用`PropertySourcesPlaceholderConfigurer`,因为Spring Boot已经提供了一个相应的功能。建议查阅Spring Boot的文档以获取更多信息。
另外,在Spring Boot中,如果你在`application.properties`文件中提供了数据库连接属性,数据库连接会自动配置,示例如下:
spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false
spring.datasource.username=yourDatabaseUsername
spring.datasource.password=yourDatabasePassword
这里有一篇关于Spring JDBC的博客文章示例:https://javamondays.com/simple-java-jdbc-example/
<details>
<summary>英文:</summary>
Remove `spring-context` dependency - you have the spring boot parent, and dont introduce dependencies of spring with a different version in general.
**IMPORTANT:** don't run SpringBoot main inside of CommandLineRunner implementing class. In general grab all that stuff from `run` method and use it in main and remove implements CommandLineRunner for everything to work.
Also you don't need `EnableAutoConfiguration` as `@SpringBootApplication` annotation includes it
You also don't need `PropertySourcesPlaceholderConfigurer` as Spring Boot provides one. Consider reading documentation on Spring Boot.
Additionally in SpringBoot connection to database is done automatically if you provide properties in `application.properties` file - like so:
spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false
spring.datasource.username=yourDatabaseUsername
spring.datasource.password=yourDatabasePassword
here is a blog post example for Spring JDBC https://javamondays.com/simple-java-jdbc-example/
</details>
# 答案2
**得分**: 0
此外,Spring Boot 正在创建容器,您会收到此错误,因为有两个上下文在不同的层次结构中运行。在 ProjectApiApplication 中添加以下字段以检索上下文:
```java
@Autowired
private ApplicationContext context;
英文:
In addition, Spring Boot is creating the container, you get this error as you have 2 contexts running not in the same hierarchy. Add this field in ProjectApiApplication to retrieve the context:
@Autowired
private ApplicationContext context;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论