@ConditionalOnProperty的目的
通常,在开发基于Spring的应用程序时,可能需要根据配置属性的存在和值有条件地创建一些bean
常见的@Conditionalxxx
开头的注解我们称之为条件注解,常见的条件注解有
- class条件注解:@ConditionalOnClass
- bean条件注解:@ConditionalOnBean
- 属性条件注解:@ConditionalOnProperty
一般是在配置类上或者是@Bean修饰的方法上,添加此注解表示一个类是否要被Spring上下文加载,若满足条件则加载,若不满足条件则不加载。
我们在application.properties中配置的各种配置,添加配置之后即生效,就是这么控制的
为了举例说明@ConditionalOnProperty的用法,接下来开发一个基本的通知系统。 为了使事情现在变得简单,假设要发送电子邮件通知。
首先,需要创建一个简单的服务来发送通知消息。 例如,考虑NotificationSender接口:
public interface NotificationSender {
String send(String message);
}
接下来,提供NotificationSender接口的实现,以发送电子邮件:
public class EmailNotification implements NotificationSender {
@Override
public String send(String message) {
return "Email Notification: " + message;
}
}
现在,看看如何使用@ConditionalOnProperty注解。 以这样的方式配置NotificationSender Bean,使其仅在定义了属性notification.service时才加载:
@Bean(name = "emailNotification")
@ConditionalOnProperty(prefix = "notification", name = "service")
public NotificationSender notificationSender() {
return new EmailNotification();
}
prefix和name属性用于表示应检查的配置属性。
最后,需要在application.properties文件中定义的自定义属性:
notification.service=email
- 如果该值为空,则返回false;
- 如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。
- 如果返回值为false,则该configuration不生效;为true则生效。
- 它主要是通过自身的两个属性来控制自动配置是否生效,这两个属性分别是name、havingValue。只有当配置文件(application.properties或者bootstrap.yml)中和name相同的属性的值和注解上havingValue的值相同时,该配置文件才会生效,如下方代码:
@Configuration
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
public class FilterConfig {
//prefix为配置文件中的前缀,
//name为配置的名字
//havingValue是与配置的值对比值,当两个值相同返回true,配置类生效.
@Bean
public FilterRegistrationBean getFilterRegistration() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new LoginFilter());
filterRegistration.addUrlPatterns("/*");
return filterRegistration;
}
}