我正在使用Spring 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来加载它。
发布于 2019-11-16 12:27:12
@ConditionalOnProperty
也适用于Controller (或Service),因为它也是Spring。
添加到您的PingController
@ConditionalOnProperty(prefix="ping.controller",
name="enabled",
havingValue="true")
@RestController
public class PingController {...}
并向application.properties打开/关闭它
ping.controller.enabled=false
发布于 2019-11-16 12:13:40
您想尝试以编程方式加载bean吗?
您可以使用以下两种机制之一访问应用程序上下文
@Autowired appContext;
或者通过扩展ApplicationAware来创建类似于豆工厂的东西
公共类ApplicationContextProvider实现ApplicationContextAware{
一旦您有了应用程序上下文的句柄,就可以通过编程方式向上下文添加bean。
发布于 2019-11-16 12:18:19
默认情况下,在Spring中,所有定义的bean及其依赖项都是在创建应用程序上下文时创建的。
我们可以通过配置带有延迟初始化的bean来关闭它,只有在需要时才会创建bean,并注入它的依赖项。
您可以通过配置application.properties
来启用延迟初始化。
spring.main.lazy-initialization=true
将属性值设置为true意味着应用程序中的所有bean都将使用延迟初始化。
除了我们使用@Lazy(false)
显式配置的bean之外,所有定义的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://stackoverflow.com/questions/58890392
复制相似问题