Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest Controller not Working

I have initialed spring boot project using start.spring.io and added WEB,JPA,H2 dependencies.

Pom file

<?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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.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-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <!-- <scope>runtime</scope> -->
    </dependency>


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

application.properties

spring.h2.console.enabled=true
security.basic.enabled=false

DemoApplication.java

@SpringBootApplication
public class DemoApplication {

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

UserController.java

@RestController
public class UserController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello";
    }

Console Log

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-02-26 11:24:28.846  INFO 4792 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on RAJAT-PC with PID 4792 (C:\Users\devra\Downloads\Compressed\demo\target\classes started by rajat in C:\Users\devra\Downloads\Compressed\demo)
2018-02-26 11:24:28.855  INFO 4792 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2018-02-26 11:24:29.018  INFO 4792 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:30.894  INFO 4792 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fa7e8c5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-26 11:24:31.720  INFO 4792 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-26 11:24:31.737  INFO 4792 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-02-26 11:24:31.740  INFO 4792 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-26 11:24:31.969  INFO 4792 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-02-26 11:24:31.970  INFO 4792 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2957 ms
2018-02-26 11:24:32.307  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-26 11:24:32.308  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-26 11:24:32.309  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-26 11:24:32.309  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-26 11:24:32.310  INFO 4792 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-02-26 11:24:32.311  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-26 11:24:32.313  INFO 4792 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'webServlet' to [/h2-console/*]
2018-02-26 11:24:33.004  INFO 4792 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:33.038  INFO 4792 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-02-26 11:24:33.196  INFO 4792 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2018-02-26 11:24:33.199  INFO 4792 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2018-02-26 11:24:33.202  INFO 4792 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2018-02-26 11:24:33.266  INFO 4792 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-26 11:24:33.517  INFO 4792 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-02-26 11:24:33.807  INFO 4792 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2018-02-26 11:24:33.816  INFO 4792 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2018-02-26 11:24:33.859  INFO 4792 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-02-26 11:24:34.365  INFO 4792 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b67034: startup date [Mon Feb 26 11:24:29 IST 2018]; root of context hierarchy
2018-02-26 11:24:34.506  INFO 4792 --- [           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)
2018-02-26 11:24:34.508  INFO 4792 --- [           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)
2018-02-26 11:24:34.568  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.569  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:34.663  INFO 4792 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-26 11:24:35.147  INFO 4792 --- [           main] b.a.s.AuthenticationManagerConfiguration : 

Using default security password: dd5212d7-4de1-4fee-9f6b-f5cd888f2f17

2018-02-26 11:24:35.222  INFO 4792 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-02-26 11:24:35.334  INFO 4792 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter$1@11c713b7, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2251b3bc, org.springframework.security.web.context.SecurityContextPersistenceFilter@602f8f94, org.springframework.security.web.header.HeaderWriterFilter@2785db06, org.springframework.security.web.csrf.CsrfFilter@603cabc4, org.springframework.security.web.authentication.logout.LogoutFilter@7a9ceddf, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4dfe8b37, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7e64c1a9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3fbe503c, org.springframework.security.web.session.SessionManagementFilter@715a70e9, org.springframework.security.web.access.ExceptionTranslationFilter@1cc8416a]
2018-02-26 11:24:35.552  INFO 4792 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-02-26 11:24:35.652  INFO 4792 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-26 11:24:35.670  INFO 4792 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 7.302 seconds (JVM running for 7.824)

as you can see spring didn't mapped the /hello url

like image 398
Rajat Avatar asked Dec 24 '22 09:12

Rajat


1 Answers

Considering that the other answers don't explain why it doesn't work as expected, here's why.

Spring uses component scanning to find eligible beans (@Repository, @Service, @Component, @Controller, ...). This is usually done by using the @ComponentScan annotation. This is explained in the core docs:

To autodetect these classes and register the corresponding beans, you need to add @ComponentScan to your @Configuration class, where the basePackages attribute is a common parent package for the two classes. (Alternatively, you can specify a comma/semicolon/space-separated list that includes the parent package of each class.)

Spring Boot, by default only scans components within the same package (and including subpackages) of the main class. This is because the @SpringBootApplication annotation includes a @ComponentScanby default, as mentioned in the Spring boot docs:

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes

If you want Spring to automatically detect your controller, you have three options:

  1. Move the controller to the com.example.demo package. This is the recommended approach according to the Spring boot documentation.

  2. Telling Spring to look at the controller package by adding a @ComponentScan annotation:

    @SpringBootApplication
    @ComponentScan({"com.example.demo", "controller"}) // Add this
    public class DemoApplication {
        // ...
    }
    
  3. Telling Spring to look at the controller package by configuring the scanBasePackages property of @SpringBootApplication:

    @SpringBootApplication(scanBasePackages = {"com.example.demo", "controller"}) // Add this
    public class DemoApplication {
        // ...
    }
    
like image 185
g00glen00b Avatar answered Jan 11 '23 01:01

g00glen00b