我想使用基本 spring 基于系统属性为 @Bean 选择 2 个类中的 1 个。一个非常淡化的变体看起来像这样
@Configuration(value = "BipBop")
@EnableWebMvc
public class BipBopConfiguration implements WebMvcConfigurer {
@Bean
public BipBop getBipBop() {
if (Boolean.getBoolean("isBip")) {
return new Bip();
} else {
return new Bop();
}
}
}
@Controller
@RequestMapping("/bipbop")
public class Bip implements BipBop {
@RequestMapping(method = RequestMethod.GET)
public void bipBop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))) {
pw.println("Bip");
pw.flush();
}
}
}
@Controller
@RequestMapping("/bipbop")
public class Bop implements BipBop {
@RequestMapping(method = RequestMethod.GET)
public void bipBop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream()))) {
pw.println("Bop");
pw.flush();
}
}
}
我看到的问题是,虽然 @Bean 选择了正确的实现,但它没有将所选的类视为 @Controller,因此当您使用 /bibpbop 访问服务器时,您会得到 404。
如果两个类都在扫描路径上,那么 spring 会将它们识别为控制器,但随后会抱怨 /bibpbop 与两个实现存在冲突。
如何告诉 spring 这样做?我看到了@ConditionalOnProperty,但据我所知,这似乎仅适用于 Spring Boot。
如果您想根据 Spring 应用程序中属性文件中的属性值有条件地启用控制器,您可以使用
@Conditional
:
假设您有一个名为
MyController
的控制器类:
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello from MyController!";
}
}
现在,让我们根据属性值有条件地启用此控制器:
@RestController
@Conditional(MyControllerCondition.class)
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello from MyController!";
}
}
请注意在
@Conditional(MyControllerCondition.class)
类上添加了 MyController
。现在,让我们创建 MyControllerCondition
类:
public class MyControllerCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// Access the property value from the environment
String enabledPropertyValue = context.getEnvironment().getProperty("my.config.enabled");
// Check if the property is defined and has the value 'true'
return "true".equalsIgnoreCase(enabledPropertyValue);
}
}
此条件类检查属性
my.config.enabled
是否已定义且值为“true”。如果不满足条件,则不会应用MyController
类。
记住在 Spring 应用程序中加载属性文件。您可以在主配置类上或通过
@PropertySource
或 application.properties
文件使用 application.yml
注释。
@Configuration
@PropertySource("classpath:myconfig.properties")
public class AppConfig {
// Configuration for loading properties file
}
现在,
MyController
将根据属性值有条件地启用,允许您在不同环境下控制其激活。