无法访问自定义Spring Boot启动器中的REST端点。

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

Can not access REST endpoint in a custom Spring Boot starter

问题

我创建了一个自定义的Spring Boot starter,使用了@RestController注解提供了一些REST端点,并且在starter中还包括了一个空的配置类和spring.factories文件。然而,当我尝试在另一个Spring Boot应用程序中使用这个starter时,无论是在使用MockMvc进行测试还是在外部工具(例如curl等)访问时,REST端点总是返回404

我想知道是否可能将REST端点分离?如果可能的话,我是否漏掉了什么?

版本1
控制器类如下:

@RestController
@RequestMapping("/foo")
public class MyController {
    @GetMapping
    public String foo() {return "bar";}
}

配置类如下:

@Configuration
@ConditionalOnClass(MyController.class)
public class MyRestAutoConfiguration {

}

在应用程序启动时,配置类被正确加载。

英文:

I created a custom Spring Boot starter which provides some REST endpoints using @RestController annotation and an emply configuration class with spring.factories file is also included in the starter. However, when I tried to use the starter in another Spring Boot application, the REST endpoints always return 404 no matter in test with MockMvc or in running accessed by external tools (curl etc.).

May I know whether it is possible to seperate REST endpoint? If it is possible, am I missing anthing?

Edition 1
The controller class looks like:

@RestController
@RequestMapping("/foo")
public class MyController {
    @GetMapping
    public String foo() {return "bar";}
}

and the configuration class looks like:

@Configuration
@ConditionalOnClass(MyController.class)
public class MyRestAutoConfiguration {

}

The configutation class is correctly loaded when the application started.

答案1

得分: 1

除了AutoConfiguration之外,你需要告诉Spring在哪里查找bean类。因此,在你的代码中,你应该将控制器描述为一个方法,或者使用@ComponentScan注解:

@Configuration
@ConditionalOnClass(MyController.class)
@ComponentScan(basePackageClasses = {MyController.class})
public class MyRestAutoConfiguration {

}

或者

@Configuration
@ConditionalOnClass(MyController.class)
public class MyRestAutoConfiguration {
    @Bean
    public MyController tradeMacAuthTokenService() {
        return new MyController();
    }
}
英文:

Apart from AutoConfiguration you need to tell Spring where to look for bean classes. So in your code you should either describe the controller as a method or use @ComponentScan annotation:

@Configuration
@ConditionalOnClass(MyController.class)
@ComponentScan(basePackageClasses = {MyController.class})
public class MyRestAutoConfiguration {

}

or

@Configuration
@ConditionalOnClass(MyController.class)
public class MyRestAutoConfiguration {
    @Bean
    public MyController tradeMacAuthTokenService() {
        return new MyController();
    }
}

huangapple
  • 本文由 发表于 2023年3月8日 17:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671213.html
匿名

发表评论

匿名网友

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

确定