SpEL @ConditionalOnProperty字符串属性为空或为空

编程入门 行业动态 更新时间:2024-10-23 04:37:23
本文介绍了SpEL @ConditionalOnProperty字符串属性为空或为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前在我的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: localhost:9000

推荐答案

您可以将 @ConditionalOnExpression 与 Spring表达式语言(SpEL)表达式为值:

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字符串属性为空或为空

本文发布于:2023-10-29 03:56:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   字符串   属性   SpEL   ConditionalOnProperty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!