Dependency injection not working on spring boot app.

huangapple go评论125阅读模式
英文:

Dependency injection not working on spring boot app

问题

I didn't figure out why this is not working, I am trying to implement a simple end point.
This is my controller:

@RestController
public class CustomerController {
    private final CustomerService customerService;

    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @GetMapping("/")
    Customer getCustomer() {
        return customerService.getCustomer();
    }
}

And this is my service:

@Component
public class CustomerService {
    public Customer getCustomer() {
        return new Customer("Anas", 23, "Monday");
    }
}

When I go to localhost:8000/ I got the next error message: "This application has no explicit mapping for /error, so you are seeing this as a fallback."

I tried to add another endpoint like this:

@GetMapping("/hi")
String sayHi() {
    return "Hello World";
}

And it's working. I assume that the getCustomer method on the controller is not working because the object is not injected properly. What am I missing?

英文:

i didn't figure out why this is not working , i am trying to implement a simple end point
this is my controller

@RestController
public class CustomerController {
    private final CustomerService customerService;


    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @GetMapping("/")
    Customer getCustomer(){
        return customerService.getCustomer();
    }
}

and this is my service

@Component
public class CustomerService {
    public Customer getCustomer(){
        return new Customer("Anas",23,"Monday");
    }

}

when i go to localhost:8000/ i got the next error message : " This application has no explicit mapping for /error, so you are seeing this as a fallback. "

i tried to add another endpoint like this


 @GetMapping("/hi")
    String sayHi(){
        return "Hello World";
    }

and its working , i assume that getCustomer method on controller not working because the object not injected well , what am missing ?

答案1

得分: 0

Ok that's was my bad, the problem was on the Customer Class, I should have added setters and getters for the fields.

英文:

Ok that's was my bad , the problem was on the Custumer Class , i should have add setters and getters for the fields

huangapple
  • 本文由 发表于 2023年3月9日 23:11:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定