This question already has answers here:
Spring Boot @autowired does not work, classes in different package
                            
                                (11个答案)
                            
                    
                2年前关闭。
        

    

我有一个非常简单的Rest Controller,仅用于测试,无法正常工作。
我在客户端使用spring boot和postman。

我的休息控制器:

@RestController
@RequestMapping("system")
public class LoginController {

    public static CouponSystemResponse csRes = new CouponSystemResponse();

    @RequestMapping(value = "login", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public CouponSystemResponse login(@RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password, @RequestParam(value = "type") String type) {
        csRes.setMessage("You have successfully logged in");
        csRes.setStatus("OK");
        return csRes;


CouponSystemResponse:

@Component
public class CouponSystemResponse {

    private String status = "";
    private String message = "";

    public CouponSystemResponse() {
    }

    public CouponSystemResponse(String status, String message) {
        super();
        this.status = status;
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "CouponSystemResponse [status=" + status + ", message=" + message + "]";
    }


邮递员输出:

postman output

网址:http://localhost:8080/system/login?username=admin&password=1234&type=ADMIN

无法弄清楚问题可能出在哪里。感谢任何帮助。

更新:我添加了主应用程序+结构的图片:

main app

最佳答案

您的所有组件都在包com.orel.couponsystem的子包中,但是带有@SpringBootApplication注释的CouponWebApplication类在包com.orel.t.couponsystem.config中,这意味着不会自动扫描任何组件。

标准解决方案:将CouponWebApplication类移到基本包中:

package com.orel.couponsystem;


替代解决方案:明确命名基本软件包:

@SpringBootApplication(scanBasePackages = "com.orel.couponsystem")

08-05 00:29