说明:模拟一个类存在,这让spring添加user对象的自定义的注解
1、定义从condition的成立条件ClassCondition注解public class ClassCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypemetadata metadata) { //需求: 导入通过注解属性值value指定坐标后创建Bean //获取注解属性值 value Map
@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@documented@Conditional(ClassCondition.class)public @interface ConditionOnClass { String[] value();}
3、定义userconfig@Configurationpublic class UserConfig { @Bean @ConditionOnClass("com.zhonglv.mycodition.domain.uesrOn") public User user(){ return new User(); }
4、测试实现类从第三步我们可以看出来 只要com.zhonglv.mycodition.domain.uesrOn这个类存在,则springIoc帮我们创建user对象
@SpringBootApplicationpublic class MycoditionApplication { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(MycoditionApplication.class, args); Object bean = run.getBean("user"); System.out.println(bean); }}
5、代码mycodition · zhonglv/springboot - 码云 - 开源中国 (gitee.com)
6、和其他的控制类注入的注解对比// @Bean// @ConditionalOnProperty(name = "zhonglv",havingValue = "yz")// public User user2(){// return new User();// }