springboot 注解动态赋值_java springboot动态给注解属性参数赋值
場景:
最近做了一個系統,使用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,而且相互之間的數據是隔離開的,互不影響。
總結
以上是生活随笔為你收集整理的springboot 注解动态赋值_java springboot动态给注解属性参数赋值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bean覆盖 springboot_Sp
- 下一篇: ios 监听一个控制器的属性_OC观察者