无法运行SpringBoot应用程序

时间:2019-06-11 09:14:04

标签: java spring eclipse spring-boot

我是Spring的新手,我必须创建一个“ HelloWorld”应用程序。经过几次尝试,我无法解决我的问题。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CiaoMondoApplication {

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

} // that's the Application

package com.example.demo;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class CiaoMondoController {

    @RequestMapping("/")
    public String index() {
        return "HelloWorld";
    }

} // and that's the controller

当我尝试使用Eclipse运行应用程序时,在输出下面:

2019-06-11 11:09:33.089  INFO 9572 --- [           main] com.example.demo.CiaoMondoApplication    : Starting CiaoMondoApplication on Asus-Mattia with PID 9572 (C:\Users\matti\eclipse-workspace\ciao-mondo\target\classes started by matti in C:\Users\matti\eclipse-workspace\ciao-mondo)
2019-06-11 11:09:33.091  INFO 9572 --- [           main] com.example.demo.CiaoMondoApplication    : No active profile set, falling back to default profiles: default
2019-06-11 11:09:33.627  INFO 9572 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-06-11 11:09:33.644  INFO 9572 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 11ms. Found 0 repository interfaces.
2019-06-11 11:09:33.895  INFO 9572 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$bb774f16] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-06-11 11:09:34.107  INFO 9572 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-06-11 11:09:34.127  INFO 9572 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-06-11 11:09:34.127  INFO 9572 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.19]
2019-06-11 11:09:34.219  INFO 9572 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-06-11 11:09:34.219  INFO 9572 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1094 ms
2019-06-11 11:09:34.271  WARN 9572 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-06-11 11:09:34.274  INFO 9572 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-06-11 11:09:34.284  INFO 9572 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-11 11:09:34.289 ERROR 9572 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

4 个答案:

答案 0 :(得分:1)

您具有数据启动依赖性,但未添加H2驱动程序,或者您想使用其他数据库,则必须至少添加:url,用户名,密码

如果您不想使用数据库,请从maven或gradle项目文件中删除启动器。

答案 1 :(得分:0)

您可能在下面提到了依赖性

  

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'

因此,Spring将在application.properties中查找数据源url,因此请将其删除,或者如果您要使用jdbc,请在application.properties中添加属性

spring.datasource.url = <jdbc-url>
spring.datasource.username = <db-username>
spring.datasource.password = <db-password>
spring.datasource.driverClassName = <db-driver>

答案 2 :(得分:-1)

如果您在应用程序中不使用任何数据源,则可以在CiaoMondoApplication类上添加以下注释

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

答案 3 :(得分:-2)

/ * *西蒙,你好 * *几个问题,您是否使用过Spring Initializr来构建项目,或者*从头开始了吗? * * https://start.spring.io/ * *是一个很好的起点: * *这是我的基本应用程序(调用sendgrid api),但这并不重要。 * * /

// Rest Application 

package com.XXXXXXX.restapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestApiApplication{

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

}

这就是我的restapi.java中的全部内容

然后我有一个控制器

sendgridcontroller.java

import java.io.IOException;


@RestController
@RequestMapping(sendGridController.BASE_URL)
public class sendGridController
{
    public static final String BASE_URL = "/api/v1/feedbacks";

    private final sendGridAPI sendGridAPIService;

    public sendGridController(sendGridAPIImpl sendGridAPIService)
    {
        this.sendGridAPIService = sendGridAPIService;
    }

    @CrossOrigin
    @PostMapping("/sendfeedback")
    public ResponseEntity<Boolean> sendFeedback(@RequestParam(name="fullname")String fullName,
                                                @RequestParam(name="subject")String subject,
                                                @RequestParam(name="email") String emailAddr,
                                                @RequestParam(name="message")String message )
    {
        Boolean     bReturn = true;

        System.out.println("fullName ="+fullName);
        System.out.println("subject ="+subject);
        System.out.println("email ="+emailAddr);
        System.out.println("message ="+message);

        try
        {
            sendGridAPIService.sendFeedbackEmail(fullName, subject, emailAddr, message);
        }
        catch(Exception e)
        {
            return new ResponseEntity<>(false,HttpStatus.BAD_GATEWAY);
        }
        return new ResponseEntity<>(bReturn, HttpStatus.OK);

    }


}

这是在自己的程序包中

接下来,我创建了一个包含两个文件的服务包

一个接口sendGridApi.java

package com.ea_optimised.restapi.services;


import org.springframework.stereotype.Service;

import java.io.IOException;


public interface sendGridAPI
{
    void sendFeedbackEmail(String fullNameme, String subject, String emailAddr, String message) throws IOException;
}

// ....最后,我实现了该接口

package com.XXXXX.restapi.services;

import com.sendgrid.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.UnknownHostException;
import java.rmi.ServerException;

@Service
public class sendGridAPIImpl implements sendGridAPI
{
    // API_KEY
    private static final String SENDGRID_API_KEY = "My key went here";

    @Override
    public void sendFeedbackEmail(String fullNameme, String subject, String emailAddr, String message) throws IOException
    {

        Email from = new Email(emailAddr);

        Email to = new Email("info@ea-optimised.co.uk");
        //      Email to = new Email("test@example.com");
        Content content = new Content("text/plain", message);
        Mail mail = new Mail(from, subject, to, content);

        SendGrid sg = new SendGrid(SENDGRID_API_KEY);
        Request request = new Request();
        try
        {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            System.out.println("****\nSTATUS="+response.getStatusCode());
            System.out.println("\n***Body :\n\n"+response.getBody());
            System.out.println("***Headers:\n\n"+response.getHeaders());
        }
        catch ( UnknownHostException e )
        {
            System.out.println("***Unknown Host Exception:\n\n");
            throw e;
        }
        catch (Exception ex)
        {
            System.out.println( "SendGrid Failed "+ex.getMessage());
            try
            {
                throw ex;
            }
            catch (IOException e)
            {
                e.printStackTrace();
                throw e;
            }
        }
    }
}

希望这会有所帮助

最后要使用Gradle或Maven吗?