SpringBoot实现注解的属性动态注入。以ElasticSearch的java查询的indexName为例

背景

最近接了个需求,需要每天从ElasticSearch(下称es)中取出数据然后持久化到mysql数据库里,而我们项目的es里的数据都是以日期作为index来存储的,那么就需要用程序每天定时进行拉取。我们用springboot的spring-boot-starter-data-elasticsearch(类似mybatis的框架)进行数据CRUD时需要为实体(entity)配置需要查询的index,配置方式为:

@Document(indexName = "xxxx-xx-xx")

那么就需要通过动态的方式每天根据日期生成indexName然后注入到@Document注解里。

本文章主要以SpringBoot的提供java查询ElasticSearch数据的样例为例子,给出一种可以动态的为注解的属性注入值得方式,下面展示下主要代码。

配置文件:conf.properties

这是用来动态存储需要注入的数据的配置文件,我们可以通过已有的一些操作properties文件的方法对该文件进行操作。

index.currentDay=2022.08.19
index.nextDay=2022.08.20

配置文件载入类:PropertyConfig.java

@Configuration
@PropertySource(value={"classpath:conf/conf.properties"})//配置文件的相对位置,根据自己实际情况设置
public class PropertyConfig {

    @Value("${index.currentDay}")//从conf.properties里注入
    private String currentDay;

    @Value("${index.nextDay}")//从conf.properties里注入
    private String nextDay;

    @Bean
    public String currentDay() {
        return currentDay;//标记一,注意,下面会有需要回来查看这里
    }
    @Bean
    public String nextDay() {
        return nextDay;
    }
}

实体类:EsNetMessage.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "#{@currentDay}")//注意,此处大括号里与上面配置文件载入类代码片段中“标记一”处的方法名相同
public class EsNetMessage {
//下面的跟本博客无关
    @Id
    @Field(type = FieldType.Text)
    public String id;

    @Field(type = FieldType.Date,name = "@timestamp")
    public String timestamp;

    @Field(type = FieldType.Text)
    public String message;
}

注入流程

conf.properties 中的properties ====> PropertyConfig.java中的成员变量 ====> EsNetMessage.java 中@Document注解里的indexName。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐