springboot读取自定义配置文件

前提:

Application.java启动类要添加注解支持,如果使用的注解是

@SpringBootApplication

那没问题,如果不是的话,还需要添加如下注解来开启配置文件读取支持

@EnableAutoConfiguration //自动加载配置信息

实现方法:

1、如果是读取application.properties文件中的值可以直接用@Value("${属性名}")来读取。

2、如果是想读取自定义的properties配置文件,直接在想要读取配置文件的类上加注解如:

@PropertySource(value="classpath:config.properties")

即可以直接使用@Value来读取

    @Value("${netty.tcp.server.host}")
    String HOST;

 如:

package com.gili.CPMasterController.netty.tcp.server;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


/**
 * description:
 * author:groot
 * date: 2019-4-10 12:07
 **/
@Component
@PropertySource(value="classpath:config.properties")
public class NettyTcpServer {

    @Value("${netty.tcp.server.port}")
    private Integer port;

}

config.properties文件

# 作为客户端请求的服务端地址
netty.tcp.server.host=127.0.0.1
# 作为客户端请求的服务端端口
netty.tcp.server.port=7000
# 作为服务端开放给客户端的端口
netty.tcp.client.port=7000

3、如果想用java bean来影射可以参考:https://www.cnblogs.com/kellyJAVA/p/8030395.html

猜你喜欢

转载自blog.csdn.net/CaptainJava/article/details/89173001