java—如何在spring上有条件地创建@controller和@service示例

avwztpqn  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(280)

我用的是Spring Boot1.5.9。
有办法打开/关闭吗 @Controller 以及 @Services ?
例如 @ConditionalOnProperty , @Conditional 为了豆子。

@ConditionalController // <--- something like this
@RestController
public class PingController {

    @Value("${version}")
    private String version;

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("version", version);
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}

然后使用一些配置bean来加载它。

ff29svar

ff29svar1#

@ConditionalOnProperty 应该也适用于控制器(或服务),因为它也是一个springbean。
添加到pingcontroller

@ConditionalOnProperty(prefix="ping.controller",
        name="enabled",
        havingValue="true")
@RestController
public class PingController {...}

和application.properties来打开/关闭它

ping.controller.enabled=false
qltillow

qltillow2#

您想尝试以编程方式加载bean吗?
您可以使用这两种机制之一访问应用程序上下文
@自动连线专用应用程序上下文appcontext;
或者通过扩展applicationware创建类似于bean工厂的东西
公共类applicationcontextprovider实现applicationcontextaware{
一旦有了应用程序上下文的句柄,就可以通过编程方式将bean添加到上下文中。

m3eecexj

m3eecexj3#

默认情况下,在spring中,所有定义的bean及其依赖项都是在创建应用程序上下文时创建的。
我们可以通过配置一个带有延迟初始化的bean来关闭它,bean只会在需要时被创建,并且它的依赖项会被注入。
您可以通过配置 application.properties .

spring.main.lazy-initialization=true

将属性值设置为true意味着应用程序中的所有bean都将使用延迟初始化。
所有定义的bean都将使用延迟初始化,但我们显式配置的bean除外 @Lazy(false) .
或者你可以通过 @Lazy 接近。当我们把 @Lazy 注解覆盖 @Configuration 类,它指示 @Bean 注解应该延迟加载。

@Lazy
@Configuration
@ComponentScan(basePackages = "com.app.lazy")
public class AppConfig {

    @Bean
    public Region getRegion(){
        return new Region();
    }

    @Bean
    public Country getCountry(){
        return new Country();
    }
}

相关问题