您的位置:首页 > 编程语言 > Java开发

006-Spring Boot自动配置-Condition、Conditional

2018-01-22 22:00 603 查看

一、接口Condition、Conditional(原理)

主要提供一下方法

boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);


true:表示装配

false:表示不装配

注解:Conditional() 参数是数组,数组内的都是true才装配

package com.lhx.spring.springboot_auto_config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.Conditional;

@SpringBootApplication
public class App2 {

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(App2.class, args);
System.out.println(context.getBeansOfType(Runnable.class));
context.close();
}
}


View Code
默认是不能装配的

可以再application.properties中添加runnable.enable=true即可装配

或者@ConditionalOnProperty(name = "runnable.enable", havingValue = "true")增加

matchIfMissing=true,表示配置没有的时候也生效

示例二:ConditionalOnClass classpath有某个类才装配

增加或删除maven,查看效果

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>


使用代码

@Bean
@ConditionalOnClass(name="com.google.gson.Gson")
public Runnable createGsonRunnable() {
return () -> {
};
}


示例三、ConditionalOnBean:根据容器中是否存在某个Bean进行装配

@Bean
@ConditionalOnBean(name="user")
public Runnable createOnBeanRunnable() {
return () -> {
};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: