Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot RestController won't work with classes which implements an interface

I'm trying to implement a Springboot REST api. and the class where I have defined the @RestController doesn't seem to be working. I have a class called MyService where it implements all the abstract methods. I have added the @RestController annotation on top of the class declaration and added the @RequestMapping annotation for the method that I need to call from the rest call. But this doesn't work. I tried this with a class which does not implement any interface and that works fine.

Here is the code

package com.my.service;

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

@RestController
public class MyService implements MyServiceInterface{

    @Override
    @RequestMapping("/age")
    public String Age() {
        return  "24";
    }
}

the code of MyServiceInterface

public interface MyServiceInterface {
    public String Age();
}

And the error I'm getting from postman is

{"timestamp":1489688505136,"status":404,"error":"Not Found","message":"No message available","path":"/age"}
like image 827
Madushika Perera Avatar asked Dec 19 '25 12:12

Madushika Perera


1 Answers

I just had the same problem during contract testing. I was very confused because there were some other @RestControllers that implemented their interface and they were correctly mapped.

Then I started my application as in prod mode and realized that the controller was correctly mapped. Extremely strange!

I was about to delete the interface and suddenly I thought of Spring proxying. Don't know why it came to my mind. Then I checked my src/test/application.properties and realized it had this property spring.aop.proxy-target-class=false. I removed it and everything is now working as expected.

Now it all makes sense to me. src/main/application.properties didn't have that property. So Spring proxying method was the default one when on prod mode. On the other hand testing was using the other Spring proxying method. I'm going to check with my teammates why it was there. I believe default Spring proxying method should be the one to go with.

like image 124
Gus Vargas Avatar answered Dec 21 '25 06:12

Gus Vargas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!