SpEL @ConditionalOnProperty字符串属性为空或为空 [英] SpEL @ConditionalOnProperty string property empty or nulll
问题描述
我目前在我的application.yaml文件中具有String属性的情况下无法创建dataSource bean.
I am currently having trouble with my dataSource bean creation on condition of String property from my applications.yaml file.
理想情况下,仅当在application.yaml文件中设置了URL时,我才想创建dataSource bean.如果bean不存在(空或null),则不应创建.我知道这种情况会检查布尔值,但是是否仍然可以检查string属性为空还是null?
Ideally, I would only like to create the dataSource bean only if the url is set in my application.yaml file. Shouldn't create the bean if its not present (empty or null). I know this condition checks on boolean but is there anyway to check if the string property is empty or null?
DatabaseConfig.java
DatabaseConfig.java
@Configuration
public class DatabaseConfig {
@Value("${database.url:}")
private String databaseUrl;
@Value("${database.username:}")
private String databaseUsername;
@Value("${database.password:}")
private String databasePassword;
protected static final String DRIVER_CLASS_NAME = "com.sybase.jdbc4.jdbc.SybDriver";
/**
* Configures and returns a datasource. Optional
*
* @return A datasource.
*/
@ConditionalOnProperty(value = "database.url")
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.url(testDatabaseUrl)
.username(testDatabaseUsername)
.password(testDatabasePassword)
.build();
}
}
application.yml(此字段为可选)
application.yml (This field will be optional)
database:
url: http://localhost:9000
推荐答案
您可以将 @ConditionalOnExpression
与
You could use @ConditionalOnExpression
with a Spring Expression Language (SpEL) expression as value:
@ConditionalOnExpression("!T(org.springframework.util.StringUtils).isEmpty('${database.url:}')")
@Bean
public DataSource dataSource() {
// snip
}
为获得更好的可读性和可重用性,您可以将其转换为注释:
For better readability and reusability you could turn this into an annotation:
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnExpression("!T(org.springframework.util.StringUtils).isEmpty('${database.url:}')")
public @interface ConditionalOnDatabaseUrl {
}
@ConditionalOnDatabaseUrl
@Bean
public DataSource dataSource() {
// snip
}
这篇关于SpEL @ConditionalOnProperty字符串属性为空或为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!