如何在春季有条件地创建@Controller和@Service实例

我正在使用Spring Boot 1.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进行加载。

预先感谢

zzxx1z2x 回答:如何在春季有条件地创建@Controller和@Service实例

@ConditionalOnProperty也应该适用于Controller(或Service),因为它也是Spring Bean。

添加到您的PingController

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

并转到application.properties以将其打开/关闭

ping.controller.enabled=false
,

您想尝试以编程方式加载Bean吗?

您可以使用两种机制之一访问应用程序上下文

  

@自动连线的私有ApplicationContext appContext;

或通过扩展ApplicationAware创建类似bean工厂的东西

  

公共类ApplicationContextProvider实现   ApplicationContextAware {

一旦拥有了应用程序上下文的句柄,就可以以编程方式将bean添加到上下文中。

,

在Spring中,默认情况下,所有定义的bean及其依赖项都是在创建应用程序上下文时创建的。

我们可以通过配置具有延迟初始化的bean来关闭它,仅在需要时才创建该bean,并注入其依赖项。

您可以通过配置application.properties来启用延迟初始化。

spring.main.lazy-initialization=true

将属性值设置为true意味着应用程序中的所有bean将使用延迟初始化。

所有定义的bean将使用延迟初始化,除了那些我们用@Lazy(false)显式配置的bean。

或者您可以通过@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();
    }
}
本文链接:https://www.f2er.com/3090406.html

大家都在问