在 Spring Boot 中,@ConditionalOnResource 注解用来判断指定资源在 classpath 中是否存在:
(1)如果指定的资源在 classpath 中存在,则匹配成功;
(2)如果指定的资源在 classpath 中不存在,则匹配失败;
创建用户和订单服务,通过 @ConditionalOnResource 注解判断在 classpath 中是否存在 init-user.txt 或 init-order.txt 文件,如果存在则创建对应的服务。
(1)创建 UserService 和 OrderService 服务,代码如下:
a、UserService.java
package com.huangx.springboot.autoconfig.service; public class UserService { // 什么也不做 }
b、OrderService.java
package com.huangx.springboot.autoconfig.service; public class OrderService { // 什么也不做 }
(2)创建用户和订单配置类,在配置类中使用 @ConditionalOnResource 注解指定它们被创建的条件。
a、UserConfig.java
package com.huangx.springboot.autoconfig.config; import com.huangx.springboot.autoconfig.service.UserService; import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnResource(resources = {"init-user.txt"}) public class UserConfig { @Bean public UserService userService() { System.out.println("UserService -> userService()"); return new UserService(); } }
b、OrderConfig.java
package com.huangx.springboot.autoconfig.config; import com.huangx.springboot.autoconfig.service.OrderService; import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnResource(resources = {"init-order.txt"}) public class OrderConfig { @Bean public OrderService orderService() { System.out.println("OrderConfig -> orderService()"); return new OrderService(); } }
(3)客户端,验证用户和订单服务是否成功创建。代码如下:
package com.huangx.springboot.autoconfig; import com.huangx.springboot.autoconfig.service.OrderService; import com.huangx.springboot.autoconfig.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class Demo9Application { @Autowired private ApplicationContext applicationContext; public static void main(String[] args) { SpringApplication.run(Demo9Application.class, args); } @GetMapping("/") public String index() { UserService userService = null; try { // 获取用户服务 userService = applicationContext.getBean(UserService.class); } catch (Exception e) { System.err.println(e.getMessage()); } OrderService orderService = null; try { // 获取订单服务 orderService = applicationContext.getBean(OrderService.class); } catch (Exception e) { System.err.println(e.getMessage()); } return "userService=" + userService + "<br/>" + "orderService=" + orderService; } }
运行上面程序,在浏览器中访问 http://localhost:8080 地址,如下图: