Я следил за примером из документации с пружинной загрузкой, и контроллер Java всегда возвращает 404 по какой -то причине < /p>
Это то, что я попробовал < /p>
package com.example.accessingdatamysql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
@PostMapping(path="/add") // Map ONLY POST Requests
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam String email) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
, который является примером, приведенным в Spring Boot здесь https://spring.io/guides/gs/accessing-data-mysql/
Тогда Я также попробовал < /p>
@RestController
@RequestMapping("/demo")
public class GreetingClass {
@GetMapping("/greeting")
public String getGreeting() {
return "hello";
}
}
< /code>
.pom Файл: < /p>
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">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.braintobytes
Finance_microservice
0.0.1-SNAPSHOT
Finance_microservice
Finance service
1.8
org.springframework.boot
spring-boot-starter-data-rest
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-webflux
mysql
mysql-connector-java
runtime
javax.persistence
javax.persistence-api
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
io.projectreactor
reactor-test
test
org.springframework.boot
spring-boot-maven-plugin
Я знаю, что это странно, я настроил все, как указано на странице, но, очевидно, ничего не работает, и я также проверил другие вопросы, похожие на это ни один из них не отвечает на мой вопрос.
Похоже, что сервер Tomcat достигается, потому что он говорит, когда я делаю вызов < /p>
o.s.web.servlet.DispatcherServlet : Completed initialization in 9 ms
Но тогда я получаю этот вызов curl 'http: // localhost: 8080/demo/greeting' и с 'http: // localhost: 8080/demo/all'
curl: удаленный сервер вернул ошибку: (404) не найден. первая строка): < /p>
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-31 08:19:16.508 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : Starting FinanceMicroserviceApplication on DESKTOP-A65224I with PID 20708 ()
2020-08-31 08:19:16.510 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : No active profile set, falling back to default profiles: default
2020-08-31 08:19:17.096 INFO 20708 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-31 08:19:17.101 INFO 20708 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-31 08:19:17.101 INFO 20708 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-31 08:19:17.150 INFO 20708 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-31 08:19:17.150 INFO 20708 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 618 ms
2020-08-31 08:19:17.465 INFO 20708 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-31 08:19:17.675 INFO 20708 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-31 08:19:17.681 INFO 20708 --- [ main] c.b.f.FinanceMicroserviceApplication : Started FinanceMicroserviceApplication in 1.328 seconds (JVM running for 1.835)
2020-08-31 08:20:21.893 INFO 20708 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-31 08:20:21.893 INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-31 08:20:21.905 INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 12 ms
< /code>
Ответ: < /p>
{
"timestamp": "2020-08-31T13:20:21.930+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/demo/greeting"
}
Это работает, если я сделаю это:
https://github.com/braintobyte/test_app ... aster/demo
Разное пример: < /strong> < /p>
Я приложил другой пример с ирархией точно одинаково, но бизнеса логика опущен: < /p>
код в контроллере: < /p>
package com.braintobytes.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.braintobytes.data.Currency;
import com.braintobytes.data.repository.CurrencyRepository;
@RestController
@RequestMapping("/demo")
public class CurrencyController {
@Autowired
private CurrencyRepository currencyRepository;
@GetMapping("/currency")
public String getCurrency() {
return "currency";
}
}
иерархия проекта:
< /p>
Тот же точный POM и в Application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword
Подробнее здесь: https://stackoverflow.com/questions/636 ... -what-i-do