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

lxkprmvk  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(47)

我想为@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 从我可以告诉。

kd3sttzy

kd3sttzy1#

如果你想在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!";
    }
}


注意在MyController类上添加了@Conditional(MyControllerCondition.class)。现在,让我们创建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应用程序中加载properties文件。您可以在主配置类上使用@PropertySource annotation,或者通过application.propertiesapplication.yml文件使用。

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


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

相关问题