主要功能当条件符合时进行装配 不符合则不进行装配
@Conditional 基于编程的条件装配
-
例如要实现 当系统用户名为
65722
时进行装配 则代码如下 -
注解类
package com.example.demo.condition;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Spring条件装配
* 当注解所标注的键值对与系统中的匹配时 才会进行装配
*
* @author mengshuo
* @since 2021-01-17 10:01:37
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnSystemCondition.class)
public @interface SystemTypeConditional {
/**
* 系统参数键
*
* @return res
*/
String key();
/**
* 系统参数值
*
* @return res
*/
String value();
}
Condition
实现类 主要用与判断是否符合装配条件
package com.example.demo.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.util.Map;
/**
* 注入条件判断类
*
* @author mengshuo
* @since 2021-01-17 10:05:41
*/
public class OnSystemCondition implements Condition {
/**
* 验证是否注解中属性是否与系统属性一致
*
* @param context 应用上下文
* @param metadata 注解信息
* @return 验证结果
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(SystemTypeConditional.class.getName());
if (attributes == null) return false;
String key = String.valueOf(attributes.get("key"));
String value = String.valueOf(attributes.get("value"));
if (key.isEmpty() || value.isEmpty()) return false;
//验证注解中的属性是否符合系统中的属性
return System.getProperty(key).equals(value);
}
}
- 需要进行
条件装配
的服务
package com.example.demo.condition;
import org.springframework.stereotype.Service;
/**
* 系统服务bean
*
* @author mengshuo
* @since 2021-01-17 11:09:17
*/
@SystemTypeConditional(key = "user.name", value = "65722")
@Service
public class SystemService {
public void print() {
System.out.println("---- 系统服务已经装配 ----");
}
}
- 启动类 这里因为没有使用
@SpringBootApplication
注解所以需要手动去指定包扫描路径
package com.example.demo.condition;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* 主类
*
* @author mengshuo
* @since 2021-01-17 11:05:37
*/
@ComponentScan(basePackages = "com.example.demo.condition")
public class ConditionRun {
public static void main(String[] args) {
ConfigurableApplicationContext run = new SpringApplicationBuilder(ConditionRun.class)
.web(WebApplicationType.NONE)
.run(args);
SystemService service = run.getBean(SystemService.class);
service.print();
run.close();
}
}
- 运行结果
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.4.RELEASE)
2021-01-17 11:48:20.823 INFO 13472 --- [ main] com.example.demo.condition.ConditionRun : Starting ConditionRun on DESKTOP-4M5DVU4 with PID 13472 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:48:20.838 INFO 13472 --- [ main] com.example.demo.condition.ConditionRun : No active profile set, falling back to default profiles: default
2021-01-17 11:48:21.057 INFO 13472 --- [ main] com.example.demo.condition.ConditionRun : Started ConditionRun in 0.743 seconds (JVM running for 1.379)
---- 系统服务已经装配 ----
与目标 VM 断开连接, 地址为: ''127.0.0.1:57658',传输: '套接字''
进程已结束,退出代码0
- 将
SystemService
中@SystemTypeConditional(key = "user.name", value = "65722")
改为@SystemTypeConditional(key = "user.name", value = "123456")
则获取不到该类型Bean
说明未被装配
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.4.RELEASE)
2021-01-17 11:48:47.705 INFO 3932 --- [ main] com.example.demo.condition.ConditionRun : Starting ConditionRun on DESKTOP-4M5DVU4 with PID 3932 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:48:47.721 INFO 3932 --- [ main] com.example.demo.condition.ConditionRun : No active profile set, falling back to default profiles: default
2021-01-17 11:48:47.924 INFO 3932 --- [ main] com.example.demo.condition.ConditionRun : Started ConditionRun in 0.686 seconds (JVM running for 1.372)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.condition.SystemService' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127)
at com.example.demo.condition.ConditionRun.main(ConditionRun.java:21)
与目标 VM 断开连接, 地址为: ''127.0.0.1:57667',传输: '套接字''
进程已结束,退出代码1
@Profile 基于配置的条件装配
-
例如要实现
profiles
中有root
字段则对SystemService
进行装配 -
SystemService
代码
package com.example.demo.condition;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
/**
* 系统服务bean
*
* @author mengshuo
* @since 2021-01-17 11:09:17
*/
@Profile("root")
@Service
public class SystemService {
public void print() {
System.out.println("---- 系统服务已经装配 ----");
}
}
- 启动类
package com.example.demo.condition;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* 主类
*
* @author mengshuo
* @since 2021-01-17 11:05:37
*/
@ComponentScan(basePackages = "com.example.demo.condition")
public class ConditionRun {
public static void main(String[] args) {
ConfigurableApplicationContext run = new SpringApplicationBuilder(ConditionRun.class)
.profiles("root")
.web(WebApplicationType.NONE)
.run(args);
SystemService service = run.getBean(SystemService.class);
service.print();
run.close();
}
}
- 运行结果
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.4.RELEASE)
2021-01-17 11:45:34.508 INFO 9744 --- [ main] com.example.demo.condition.ConditionRun : Starting ConditionRun on DESKTOP-4M5DVU4 with PID 9744 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:45:34.508 INFO 9744 --- [ main] com.example.demo.condition.ConditionRun : The following profiles are active: root
2021-01-17 11:45:34.758 INFO 9744 --- [ main] com.example.demo.condition.ConditionRun : Started ConditionRun in 0.72 seconds (JVM running for 1.386)
---- 系统服务已经装配 ----
与目标 VM 断开连接, 地址为: ''127.0.0.1:57639',传输: '套接字''
进程已结束,退出代码0
- 若将
profiles
中root
删除或者改为其他 则运行结果为
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.4.RELEASE)
2021-01-17 11:46:04.223 INFO 3084 --- [ main] com.example.demo.condition.ConditionRun : Starting ConditionRun on DESKTOP-4M5DVU4 with PID 3084 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:46:04.226 INFO 3084 --- [ main] com.example.demo.condition.ConditionRun : The following profiles are active: root1
2021-01-17 11:46:04.428 INFO 3084 --- [ main] com.example.demo.condition.ConditionRun : Started ConditionRun in 0.675 seconds (JVM running for 1.314)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.condition.SystemService' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127)
at com.example.demo.condition.ConditionRun.main(ConditionRun.java:22)
与目标 VM 断开连接, 地址为: ''127.0.0.1:57648',传输: '套接字''
进程已结束,退出代码1