spring 基于配置开关的@Controller的条件摄取

lxkprmvk  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(113)

我想为@Bean选择2个类中的一个,基于使用基本spring的系统属性。

  1. @Configuration(value = "BipBop")
  2. @EnableWebMvc
  3. public class BipBopConfiguration implements WebMvcConfigurer {
  4. @Bean
  5. public BipBop getBipBop() {
  6. if (Boolean.getBoolean("isBip")) {
  7. return new Bip();
  8. } else {
  9. return new Bop();
  10. }
  11. }
  12. }
  13. @Controller
  14. @RequestMapping("/bipbop")
  15. public class Bip implements BipBop {
  16. @RequestMapping(method = RequestMethod.GET)
  17. public void bipBop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  18. try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))) {
  19. pw.println("Bip");
  20. pw.flush();
  21. }
  22. }
  23. }
  24. @Controller
  25. @RequestMapping("/bipbop")
  26. public class Bop implements BipBop {
  27. @RequestMapping(method = RequestMethod.GET)
  28. public void bipBop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29. try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))) {
  30. pw.println("Bop");
  31. pw.flush();
  32. }
  33. }
  34. }

字符串
我看到的问题是,虽然@Bean选择了正确的实现,但它没有将所选的类视为@Controller,因此当您使用/bipbop访问服务器时,您会得到404。
如果两个类都在扫描路径上,那么spring会将它们识别为控制器,但随后会抱怨/bipbop与两个实现存在冲突。
如何告诉Spring这样做?我看到的@ConditionalOnProperty,但这似乎只是为Spring Boot 从我可以告诉。

kd3sttzy

kd3sttzy1#

如果你想在Spring应用程序中根据属性文件中的属性值有条件地启用控制器,你可以使用@Conditional
假设你有一个名为MyController的控制器类:

  1. @RestController
  2. public class MyController {
  3. @GetMapping("/hello")
  4. public String hello() {
  5. return "Hello from MyController!";
  6. }
  7. }

字符串
现在,让我们根据属性值有条件地启用这个控制器:

  1. @RestController
  2. @Conditional(MyControllerCondition.class)
  3. public class MyController {
  4. @GetMapping("/hello")
  5. public String hello() {
  6. return "Hello from MyController!";
  7. }
  8. }


注意在MyController类上添加了@Conditional(MyControllerCondition.class)。现在,让我们创建MyControllerCondition类:

  1. public class MyControllerCondition implements Condition {
  2. @Override
  3. public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  4. // Access the property value from the environment
  5. String enabledPropertyValue = context.getEnvironment().getProperty("my.config.enabled");
  6. // Check if the property is defined and has the value 'true'
  7. return "true".equalsIgnoreCase(enabledPropertyValue);
  8. }
  9. }


此条件类检查属性my.config.enabled是否已定义且值为“true”。如果不满足条件,则不会应用MyController类。
记住在Spring应用程序中加载properties文件。您可以在主配置类上使用@PropertySource annotation,或者通过application.propertiesapplication.yml文件使用。

  1. @Configuration
  2. @PropertySource("classpath:myconfig.properties")
  3. public class AppConfig {
  4. // Configuration for loading properties file
  5. }


现在,MyController将根据属性值有条件地启用,允许您在不同的环境中控制其激活。

展开查看全部

相关问题