Не удается запустить приложение SpringBoot - PullRequest
0 голосов
/ 11 июня 2019

Я новичок в 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 ]

1 голос
/ 11 июня 2019

У вас есть зависимость запуска данных, но вы не добавили драйвер для H2, или вы хотите использовать другую базу данных, тогда вам нужно добавить как минимум: url, имя пользователя, пароль

Если вы не хотите использовать базу данных, удалите стартовый файл из вашего проекта maven или gradle.

0 голосов
/ 11 июня 2019

/ * * Привет Саймон, * * Пара вопросов, вы использовали Spring Initializr для создания проекта или * сделали это с нуля? * * https://start.spring.io/ * * Это хорошее место для начала: * * Вот мое основное приложение (для вызова API sendgrid), но это не имеет значения. * * /

// 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?

0 голосов
/ 11 июня 2019

Вы могли упомянуть ниже зависимость

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

Итак, Spring будет искать URL источника данных в application.properties, поэтому удалите его или, если вы хотите работать с jdbc, добавьте свойства в application.properties

spring.datasource.url = <jdbc-url>
spring.datasource.username = <db-username>
spring.datasource.password = <db-password>
spring.datasource.driverClassName = <db-driver>
0 голосов
/ 11 июня 2019

Если вы не используете какой-либо источник данных в своем приложении, вы можете поместить следующую аннотацию в CiaoMondoApplication class

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...