/** * 上传文件到本地 * @since 2024-06-13 * 堆代码 duidaima.com */ public class FileUploader implements Uploader { @Override public String upload(File file) { //上传文件到本地,并返回绝对路径 return null; } } /** * 上传文件到OSS * @since 2024-06-13 */ public class OSSUploader implements Uploader { @Override public String upload(File file) { //上传文件到云端,并返回绝对路径 return null; } }2、然后编写一个服务配置类,根据不同的环境,创建不同的实现类
@Configuration public class AppConfig { @Bean @Profile("dev") public Uploader initFileUploader() { System.out.println("初始化一个上传到本地的bean"); return new FileUploader(); } @Bean @Profile("!dev") public Uploader initOSSUploader() { System.out.println("初始化一个上传到云端的bean"); return new OSSUploader(); } }3、最后,运行程序
spring.profiles.active=dev2.2、Conditional
public class SMSEnvCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return "true".equalsIgnoreCase(context.getEnvironment().getProperty("enable.sms")); } }2、创建一个发短信的服务
@Component @Conditional(SMSEnvCondition.class) public class SendMessageService { //... }3、在application.properties文件中,添加配置变量enable.sms
enable.sms=true当enable.sms为true的时候,会创建SendMessageService对象,否则不创建。
ConditionalOnExpression:根据表达式判断条件是否生效
@Component @ConditionalOnProperty(name="enable.sms", havingValue="true") public class SendMessageService { //... }当enable.sms的值等于true时,会实例化SendMessageService对象;反之,不会创建对象。是不是超级简单~~~
@Component @ConditionalOnProperty(name = "file.storage", havingValue = "file", matchIfMissing = true) public class FileUploader implements Uploader { @Override public String upload(File file) { //上传文件到本地,并返回绝对路径 return null; } } @Component @ConditionalOnProperty(name = "file.storage", havingValue = "oss") public class OSSUploader implements Uploader { @Override public String upload(File file) { //上传文件到云端,并返回绝对路径 return null; } }当file.storage配置值为file,会加载FileUploader类;当file.storage配置值为oss,会加载OSSUploader类。其中@ConditionalOnProperty中的matchIfMissing参数表示,当没有找到对应配置参数时,会默认加载当前类,也就是FileUploader类。