简体   繁体   English

来自Maven依赖项的Spring Boot RestController不起作用

[英]spring boot RestController from maven dependency does not work

I have a following controller in my microservices-core project: 我的微服务核心项目中有一个以下控制器:

package com.XYZ.microservices.core.api.version;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/version")
public class VersionController {

    @Autowired
    private VersionService versionService;

    @RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Version getVersion() {
        return versionService.getVersion();
    }
}

I have another project called product-service. 我还有另一个名为产品服务的项目。 I am importing microservices-core to product-service like this: 我将微服务核心导入到产品服务中,如下所示:

dependencies {
        compile("com.XYZ:microservices-core:1.0.0-RELEASE")
        ...
}

Now, I am initializing product-service application like this: 现在,我正在初始化产品服务应用程序,如下所示:

@SpringBootApplication
public class ProductServiceApplication {

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

The classes in microservices-core are available in product-service. microservices-core中的类在product-service中可用。 But I am not able to GET localhost:8080/version when I run product-service. 但是运行产品服务时,我无法获取localhost:8080 / version。 Can someone help? 有人可以帮忙吗?

My guess is your main application class package is not in the same package as the controller class. 我的猜测是您的主要应用程序类包与控制器类不在同一个包中。

Add ComponentScan annotation to your main class to scan all subpackages for components: ComponentScan批注添加到您的主类中,以扫描所有子包中的组件:

@SpringBootApplication
@ComponentScan({"com.XYZ.microservices.core"})
public class ProductServiceApplication {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM