我想为@Bean
选择2个类中的一个,基于使用基本spring的系统属性。
@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
,因此当您使用/bipbop
访问服务器时,您会得到404。
如果两个类都在扫描路径上,那么spring会将它们识别为控制器,但随后会抱怨/bipbop
与两个实现存在冲突。
如何告诉Spring这样做?我看到的@ConditionalOnProperty
,但这似乎只是为Spring Boot 从我可以告诉。
1条答案
按热度按时间kd3sttzy1#
如果你想在Spring应用程序中根据属性文件中的属性值有条件地启用控制器,你可以使用
@Conditional
:假设你有一个名为
MyController
的控制器类:字符串
现在,让我们根据属性值有条件地启用这个控制器:
型
注意在
MyController
类上添加了@Conditional(MyControllerCondition.class)
。现在,让我们创建MyControllerCondition
类:型
此条件类检查属性
my.config.enabled
是否已定义且值为“true”。如果不满足条件,则不会应用MyController
类。记住在Spring应用程序中加载properties文件。您可以在主配置类上使用
@PropertySource
annotation,或者通过application.properties
或application.yml
文件使用。型
现在,
MyController
将根据属性值有条件地启用,允许您在不同的环境中控制其激活。