springboot-14-自定义properties文件值注入javaBean中
被这个问题困扰了好几天....
在spring中, 从资源文件向bean中注入值非常简单, 只需要properties文件被spring加载, 然后在被spring管理的类写响应的属性, 然后 @Value("${SERVER_URL") 的方式就可以取到值了
在springboot中, 同样的方式也可以取到值, 但未免感觉有点low, 所以苦苦寻觅好几天,
在这儿以创建一个ESClient的方式进行说明:
0, 在pom.xml中导入依赖
为什么叫0呢, 因为你不导入, 加上(1) 的注解, 会有警告黄线提示你导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
1, 在App.java中加入注解
@EnableConfigurationProperties
我的类上有注解, @EnableAutoConfiguration, 所以没有加
2, 将 elasticsearch.properties 文件放置在 source/ES/下

3, 然后在需要注入的类上加入注解:
@Component
@ConfigurationProperties(prefix = "escluster.transport")
@PropertySource("classpath:ES/elasticsearch.properties")
因为 5.1.0 以后, 取消了ConfigurationProperties中location属性, 所以使用 PropertySource 进行了替代, 也正是这个注解需要步骤一种的注解
查了挺多博客才找到原因: http://www.jianshu.com/p/b71845c142d0, 为此还找了个vpn, 挺好用, 想要可以联系 wenbronk@163.com
4, 完整的ESClient类代码
package com.iwhere.easy.travel.tool; import java.net.InetSocketAddress; import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; /**
* 获取esclient工具类
*
* @author wenbronk
* @time 2017年4月5日 上午11:29:52 2017
*/
@Component
@ConfigurationProperties(prefix = "escluster.transport")
@PropertySource("classpath:ES/elasticsearch.properties")
public class ESClient {
private Logger LOGGER = LoggerFactory.getLogger(ESClient.class); private String name;
private String ip;
private int port; private boolean sniff;
private boolean ignore_cluster_name;
private int ping_timeout;
private int nodes_sampler_interval; /**
* @return
*/
@Bean(name = "client")
public Client getEsClient() {
Client client = null;
Settings settings = Settings.builder().put("cluster.name", name)
.put("client.transport.sniff", sniff)
// .put("client.transport.ignore_cluster_name",
// ESCLUSTER_IGNORE_NAME)
// .put("client.transport.ping_timeout", ESCLUSTER_TIMEOUT)
// .put("client.transport.nodes_sampler_interval",
// ESCLUSTER_INTERVAL)
.build();
client = new PreBuiltTransportClient(settings).addTransportAddress(
new InetSocketTransportAddress(new InetSocketAddress(ip, port)));
LOGGER.info("transport client has created ");
return client;
} public Logger getLOGGER() {
return LOGGER;
} public void setLOGGER(Logger lOGGER) {
LOGGER = lOGGER;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getIp() {
return ip;
} public void setIp(String ip) {
this.ip = ip;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public boolean isSniff() {
return sniff;
} public void setSniff(boolean sniff) {
this.sniff = sniff;
} public boolean isIgnore_cluster_name() {
return ignore_cluster_name;
} public void setIgnore_cluster_name(boolean ignore_cluster_name) {
this.ignore_cluster_name = ignore_cluster_name;
} public int getPing_timeout() {
return ping_timeout;
} public void setPing_timeout(int ping_timeout) {
this.ping_timeout = ping_timeout;
} public int getNodes_sampler_interval() {
return nodes_sampler_interval;
} public void setNodes_sampler_interval(int nodes_sampler_interval) {
this.nodes_sampler_interval = nodes_sampler_interval;
}
}
现在就完成了springboot从properties文件向bean中注值问题的解决
写在最后, 不要在构造方法中使用 @Autowired的值, 猜测应该是对象创建完成后才会对值进行导入, 再次坑了很久
对于yml格式的文件, 注入值的方式为:
@Component
@ConfigurationProperties(prefix = "interface.server.url")
// @PropertySource("classpath:server_url.yml")
public class BaseInterfaceUtil {
private static Logger LOGGER = LoggerFactory.getLogger(BaseInterfaceUtil.class); private String geosot; @setGet
}
yml文件的书写格式:

如果是单独的properties文件, 也可以使用
ResourceBundle.getBundle("fileName")
他会默认加载 classpath: 下的 fileName.properties文件, 并存入一个map集合中
5, 如果直接在application.yml中写配置, 可以
package rdp.hive.phone.job.conf; import com.google.common.collect.Lists;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component; import java.util.ArrayList;
import java.util.Arrays; /**
*
*/ @Component
@ConfigurationProperties(prefix = "es.connect")
public class EsClientConfig { private String hosts;
private Integer port; @Bean
@ConditionalOnMissingBean(RestHighLevelClient.class)
public RestHighLevelClient getRestHighLevelClient() {
ArrayList<HttpHost> hostsArray = Lists.newArrayList();
Arrays.stream(hosts.split(", *")).forEach(host -> {
hostsArray.add(new HttpHost(host, port, "http"));
});
return new RestHighLevelClient(RestClient.builder(hostsArray.toArray(new HttpHost[])));
} public String getHosts() {
return hosts;
} public void setHosts(String hosts) {
this.hosts = hosts;
} public Integer getPort() {
return port;
} public void setPort(Integer port) {
this.port = port;
}
}
然后在yml中配置:

系列原创, 转载请注明出处, 谢谢 @wenbronk
springboot-14-自定义properties文件值注入javaBean中的更多相关文章
- 尚硅谷springboot学习9-配置文件值注入
首先让我想到的是spring的依赖注入,这里我们可以将yaml或者properties配置文件中的值注入到java bean中 配置文件 person: lastName: hello age: 18 ...
- SpringBoot读取application.properties文件
http://blog.csdn.net/cloume/article/details/52538626 Spring Boot中使用自定义的properties Spring Boot的applic ...
- SpringBoot @Value读取properties文件的属性
SpringBoot在application.properties文件中,可以自定义属性. 在properties文件中如下示: #自定义属性 mail.fromMail.addr=lgr@163.c ...
- JAVA中自定义properties文件介绍
Gradle中的使用 1. 使用gradle.properties buid.gradle 和 gradle.properties可以项目使用,在同一个项目中,build.gradle可以直接获取其同 ...
- JAVAEE——SpringBoot配置篇:配置文件、YAML语法、文件值注入、加载位置与顺序、自动配置原理
转载 https://www.cnblogs.com/xieyupeng/p/9664104.html @Value获取值和@ConfigurationProperties获取值比较 @Confi ...
- 3springboot:springboot配置文件(配置文件、YAML、属性文件值注入<@Value、@ConfigurationProperties、@PropertySource,@ImportResource、@Bean>)
1.配置文件: springboot默认使用一个全局配置文件 配置文件名是固定的 配置文件有两种(开头均是application,主要是文件的后缀): ->application.prope ...
- SpringBoot的读取properties文件的方式
转载:https://www.imooc.com/article/18252一.@ConfigurationProperties方式 自定义配置类:PropertiesConfig.java pack ...
- 170720、springboot编程之properties文件讲解
但是在实际开发过程中有更复杂的需求,我们在对properties进一步的升华.在本篇博客中您将会学到如下知识(这节中有对之前的知识的温故,对之前的升华): (1) 在application.prope ...
- 161216、使用spring的DefaultResourceLoader自定义properties文件加载工具类
import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; imp ...
随机推荐
- nodejs+express+mysql+handsontable
介绍:做一个医疗数据分析的系统 现在看是写后端的功能,按照PHP的功能,在node上一个个实现. 1.route引用controller,controller引用model,所以会先执行model可以 ...
- Django开发Web监控工具-pyDash
今天发现了一个比较有意思的监控工具,是基于Django开发的,开发大牛已经开放了源代码,向大牛致敬,同时研究研究,目前感觉这个监控比较直观,可以针对个人服务器使用,同时涉及的环境比较简单,部署起来 ...
- boot分区剩余空间不足
Linux boot分区用于存放内核文件以及Linux一些启动配置文件,一般情况下分区大小为500M足够使用,如果出现空间不足的问题可以使用以下方法来解决. 查看已经安装的内核 dpkg --ge ...
- 用C#开发的双色球走势图(原创)值得园友拥有
首先声明,个人纯粹无聊之作,不作商业用途. 我相信每个人都拥有一个梦想那就是有朝一日能中500W,这个也一直是我的梦想,并默默每一期双色球或多或少要贡献自己一点点力量,本人并不属于那种铁杆的彩票迷,每 ...
- 安装CentOS桌面环境
CentOS 作为服务器的操作系统是很常见的,但是因为需要稳定而没有很时髦的更新,所以很少做为桌面环境.在服务器上通常不需要安装桌面环境,最小化地安装 CentOS(也就是 minimal CentO ...
- C#内存释放(垃圾回收)
今天写了个很小的程序,程序的功能仅仅是截图,但是如果长时间开启并截图的时候,程序会变的很大,从刚开始的运行在任务管理器中只有十几K大小,运行一段时间后在任务管理器中看到程序可以达到1G或2G甚至更大: ...
- C# 一些代码小结--使用文件记录日志
C# 一些代码小结--使用文件记录日志 public class FaceLog { public static void AppendInfoLog(string errMsg) { try { s ...
- 如何优化代码中大量的if/else,switch/case?
前言 随着项目的迭代,代码中存在的分支判断可能会越来越多,当里面涉及到的逻辑比较复杂或者分支数量实在是多的难以维护的时候,我们就要考虑下,有办法能让这些代码变得更优雅吗? 正文 使用枚举 这里我们简单 ...
- String-680. Valid Palindrome II
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a pa ...
- hdoj1373 Channel Allocation(极大团)
题意是有若干个接收器,给出每个接收器的相邻接收器.相邻的接收器不能使用同一信号频道.问所需要的信号频道数. 求该无向图的极大团. #include<iostream> #include&l ...