15

I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar log below:

2017年11月13日 17:37:50.921 INFO 6503 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017年11月13日 17:37:51.061 INFO 6503 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017年11月13日 17:37:51.066 INFO 6503 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017年11月13日 17:37:51.067 INFO 6503 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017年11月13日 17:37:51.126 INFO 6503 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017年11月13日 17:37:51.127 INFO 6503 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017年11月13日 17:37:51.188 INFO 6503 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;
import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {
 @Autowired
 private Environment env;
 public static void main(String[] args) {
 SpringApplication.run(JobScheduleApplication.class, args);
 }
 @Bean
 public DataSource dataSource() {
 DruidDataSource dataSource = new DruidDataSource();
 dataSource.setUrl(env.getProperty("spring.datasource.url"));
 dataSource.setUsername(env.getProperty("spring.datasource.username"));
 dataSource.setPassword(env.getProperty("spring.datasource.password"));
 dataSource.setInitialSize(2);
 dataSource.setMaxActive(20);
 dataSource.setMinIdle(0);
 dataSource.setMaxWait(60000);
 dataSource.setValidationQuery("SELECT 1");
 dataSource.setTestOnBorrow(false);
 dataSource.setTestWhileIdle(true);
 dataSource.setPoolPreparedStatements(false);
 return dataSource;
 }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
 @RequestMapping(method = RequestMethod.GET)
 public JSONObject HelloWorld() {
 JSONObject res = new JSONObject();
 LOGGER.info("HelloWorld Test!");
 res.put("data", "hello world!");
 res.put("errCode", 0);
 return res;
 }
}

the 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.teachermate</groupId>
 <artifactId>job-scheduler</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>jobSchedule</name>
 <description>job schedule for teachermate</description>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>1.5.7.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 <java.version>1.8</java.version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-jdbc</artifactId>
 <exclusions>
 <exclusion>
 <groupId>org.apache.tomcat</groupId>
 <artifactId>tomcat-jdbc</artifactId>
 </exclusion>
 </exclusions>
 </dependency>
 <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>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context-support</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-configuration-processor</artifactId>
 <optional>true</optional>
 </dependency>
 <dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.39</version>
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.30</version>
 </dependency>
 <dependency>
 <groupId>org.quartz-scheduler</groupId>
 <artifactId>quartz</artifactId>
 <version>2.2.1</version>
 </dependency>
 <dependency>
 <groupId>com.google.guava</groupId>
 <artifactId>guava</artifactId>
 <version>23.2-jre</version>
 </dependency>
 <dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.3.6</version>
 </dependency>
 <dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>druid</artifactId>
 <version>1.0.19</version>
 </dependency>
 </dependencies>
 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 <configuration>
 <executable>true</executable>
 </configuration>
 </plugin>
 </plugins>
 </build>
</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.


update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {
 private static final String template = "Hello, %s!";
 private final AtomicLong counter = new AtomicLong();
 @RequestMapping("/greeting")
 public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
 return new Greeting(counter.incrementAndGet(),
 String.format(template, name));
 }
 @RequestMapping(method = RequestMethod.GET)
 public JSONObject HelloWorld() {
 JSONObject res = new JSONObject();
 res.put("data", "hello world!");
 res.put("errCode", 0);
 return res;
 }
}

it works fine!

asked Nov 13, 2017 at 10:26
4
  • Add the test controller in the same package as GreetingController and try Commented Nov 13, 2017 at 10:47
  • Maybe there is a conflict between fastjson and jackson in spring-boot-web . Please again remove fastjson dependency and check whether it works well or not. Commented Nov 13, 2017 at 10:47
  • @GurkanYesilyurt the rest api works fine before, at that time I have used the fastjson library Commented Nov 13, 2017 at 10:55
  • @shakeel I have tried, it works fine Commented Nov 13, 2017 at 11:13

9 Answers 9

7

I finally figured it out.

I write a while loop in a method which has the @PostConstruct Annotation.It must block the spring main process, causing the rest controller not being loaded.

How foolish am I.

answered Nov 13, 2017 at 12:57
Sign up to request clarification or add additional context in comments.

1 Comment

Same here. I was starting a kstreams topology in the @PostConstruct which would run on indefinitely
5

Could it be because it cant find the controller ? If yes, may you try this using @ComponentScan ? @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

@SpringBootApplication
@ComponentScan(basePackageClasses = TestController.class)
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {
//Your code here
}
answered Nov 13, 2017 at 10:49

1 Comment

I add @ComponentScan(basePackageClasses = TestController.class, basePackages = "com.teachermate"), because I have other component need to be register as beans. But it didn't work
4

So basically your application main method is not able to identify the controller,service,entity etc. First please make sure you are using for their respective classes. like @Restcontroller for your controller class

@RestController
@service
@Entity
@JPARepository

Also, Make sure you are asking the spring boot application to check for these classes in the different packages

@ComponentScan({"com.funky.classes.controller","com.funky.classes.service"})
@EntityScan("com.funky.classes.model")
@EnableJpaRepositories("com.funky.classes.repository")
@SpringBootApplication()... 
answered Mar 27, 2018 at 17:37

Comments

0

Create a person class to test:

public class Person{
private String name;
private String nickname;
//getters and setters...
}

In your method of controller, try this:

 @GetMapping(value ="/test", consumes = {MediaType.APPLICATION_JSON_VALUE })
 public ResponseEntity<?> helloWorld() {
 Person person = new Person();
 person.setName("test");
 person.setNickname("test2");
 return ResponseEntity.status(HttpStatus.OK).body(person);
 }
answered Nov 13, 2017 at 10:37

1 Comment

what is need to add person class here. You can directly hit the url and check.
0

There are a couple of things missing here. First, you need to add RequestMapping to the defined function and for returning the JSONObject, you need to use the @ResponseBody Annotation along with ResponseEntity as the return type of the function Example Code:

@RequestMapping(value = "/testing", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON)
public @ResponseBody ResponseEntity<JSONObject> HelloWorld() {
 JSONObject res = new JSONObject();
 LOGGER.info("HelloWorld Test!");
 res.put("data", "hello world!");
 res.put("errCode", 0);
 return ResponseEntity.status(HttpStatus.OK).body(res);
}

The @RequestMapping Annotation can used on both Function level as well as Class Level. Class Level Annotation value should be prepended to all function @RequestMapping Annotation values in the final REST Endpoint.

answered Nov 13, 2017 at 10:45

1 Comment

When using @RestController the @ResponseBody is implied.
0

Good day !

 The @RequestMapping annotation should be made in this way
@RestController
public class TestController {
 @RequestMapping(value = "/test", method = RequestMethod.GET)
 public JSONObject HelloWorld() {
 JSONObject res = new JSONObject();
 LOGGER.info("HelloWorld Test!");
 res.put("data", "hello world!");
 res.put("errCode", 0);
 return res;
 }
}

but that way you get the same result

@RestController
public class TestController {
 @RequestMapping(value = "/test", method = RequestMethod.GET, 
 produces = MediaType.APPLICATION_JSON_VALUE )
 public HashMap HelloWorld() {
 HashMap<String, String> res = new HashMap<String, String>(); 
 res.put("data", "hello world");
 res.put("errorCode", "0");
 return res;
 }
}

url -> localhost:{port}/test

References:

answered Nov 13, 2017 at 11:15

1 Comment

The second code block will not compile because of differences in return type.
0

I had the same problem with springboot 3.0.1, especially ones which use tomcat 10.14. You will have to use this format on your springboot application class if not it will throw white label page.

here is the format to try. Put on the springboot class application

@EnableAutoConfiguration
@SpringBootApplication
@AutoConfigurationPackage
@ComponentScan(basePackageClasses = {UserResourceController.class, UserService.class, Repo.class})
public class DemoApplication {
 public static void main(String[] args) {
 SpringApplication.run(DemoApplication.class, args);
 }
}
answered Jan 2, 2023 at 17:33

Comments

0

@SpringBootApplication annotation comes with package scanning and all we don't need to repeat it. On your controllers, add requestpath separately as below,

@RestController()
@RequestMapping("/employees")
public class EmployeeController {
 // methods
}
However, if you add ```
@RestController("/employees")```
only to your controllers that won't work. 
answered Nov 15, 2024 at 2:47

Comments

-1

Try applying the request mapping annotation as described below.

@RestController
public class TestController {
 @RequestMapping(method = RequestMethod.GET)
 @RequestMapping(path = "/test")
 public JSONObject HelloWorld() {
 JSONObject res = new JSONObject();
 LOGGER.info("HelloWorld Test!");
 res.put("data", "hello world!");
 res.put("errCode", 0);
 return res;
 }
}

Also, check this link below for more examples: http://www.baeldung.com/spring-requestmapping

answered Nov 13, 2017 at 10:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.