springboot 注解动态赋值_java springboot动态给注解属性参数赋值

该博客介绍了在Spring Boot项目中,开发和正式环境共用一个Elasticsearch的实现方法。通过在配置文件定义不同环境的索引名称,编写配置类读取索引名称值,最后在Elasticsearch实体类注解上使用,实现了两环境数据隔离且共用一个Elasticsearch。

场景:

最近做了一个系统,使用Elasticsearch做了全文搜索,系统分为开发环境和正式环境,正式环境供公司内部使用,因为服务器资源不太充裕,决定开发环境和正式环境共用一个Elasticsearch,不同环境仅以索引名称(indexName)进行区分。即:一个Elasticsearch供两个系统使用。

实现:

1.在配置文件里定义索引名称

开发环境的配置:application-dev.yml

spring:

data:

elasticsearch:

repositories:

enabled: true

cluster-nodes: 172.16.11.109:9300

cluster-name: elasticsearch

article-index-name: article

正式环境的配置:application-prod.yml

spring:

data:

elasticsearch:

repositories:

enabled: true

cluster-nodes: 172.16.11.109:9300

cluster-name: elasticsearch

article-index-name: article-prod

通过以上配置文件可以看出,两个环境只有索引名称是不一样的(索引名称article-index-name,属于自己定义的配置项,这里为了便于统一管理,将其与Elasticsearch的配置放在一起)。

2.编写一个配置类,用于读取配置文件中索引名称的值

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class ArticleIndexConfig{

@Value("${spring.data.elasticsearch.article-index-name}")

private String articleIndexName;

@Bean

public String articleIndexName(){

return articleIndexName;

}

}

3.在Elasticsearch的实体类的注解上使用

import org.springframework.data.annotation.Id;

import org.springframework.data.elasticsearch.annotations.Document;

import org.springframework.data.elasticsearch.annotations.Field;

import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;

@Document(indexName = "#{@articleIndexName}", type = "java")

public class ArticleModel implements Serializable{

private static final long seriaVersionUID = 6320548148250372656L;

@Id

private String rowId;

@Field(type = FieldType.text)

private String title;

@Field(type = FieldType.text)

private String content;

//getter和setter省略

//...

}

4.经过以上的动作,两个环境(开发环境和正式环境)就可以共用一个Elasticsearch,而且相互之间的数据是隔离开的,互不影响。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值