英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论