Java_配置文件读取

Java_配置文件读取

大多项目开发都需要使用到配置文件读取,但由于本人都是使用的使用的时候才去搜一下用法(是的,不咋记),因此本文遍历记录下用到的配置文件读取方式,防止某些项目某些方式无效不可用(往往因为冲突)

@Configuration

application.yml

socketio:
  host: localhost
  port: 1881

SocketIoConfig

@Data
@Configuration
public class SocketIOConfig {
    @Value("${socketio.host}")
    private String host;
    @Value("${socketio.port}")
    private String port;
}

配置信息调用

@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {
    @Resource
    private SocketIOConfig socketIOConfig;

	@Override
    public void connetion() {
        String url = "http://" + socketIOConfig.getHost() + ":" + socketIOConfig.getPort();
        System.out.println(url);
    }
}

读取结果

http://=localhost:1881

@PropertySource、@ConfigurationProperties

统一父级(使用@ConfigurationProperties)

fuxa.yml
socketio:
  host: localhost
  port: 1881
SocketIoConfig
@Data
@Component
@ConfigurationProperties(prefix = "socketio")
@PropertySource(value = {"classpath:fuxa.yml"})
public class SocketIOConfig {
    @Value("${host}")
    private String host;
    @Value("${port}")
    private String port;
}
配置信息调用
@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {
    @Resource
    private SocketIOConfig socketIOConfig;

	@Override
    public void connetion() {
        String url = "http://" + socketIOConfig.getHost() + ":" + socketIOConfig.getPort();
        System.out.println(url);
    }
}
读取结果

http://=localhost:1881

非统一父级(不使用@ConfigurationProperties)

不使用@ConfigurationProperties实际读取的还是默认的application.yml

application.yml
socketio01:
  host: localhostAAA
socketio02:
  port: 1885
fuxa.yml
socketio01:
  host: localhost
socketio02:
  port: 1881
SocketIoConfig
@Data
@Component
@PropertySource(value = {"classpath:fuxa.yml"})
public class SocketIOConfig {
    @Value("${socketio01.host}")
    private String host;
    @Value("${socketio02.port}")
    private String port;
}
配置信息调用
@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {
    @Resource
    private SocketIOConfig socketIOConfig;

	@Override
    public void connetion() {
        String url = "http://" + socketIOConfig.getHost() + ":" + socketIOConfig.getPort();
        System.out.println(url);
    }
}
读取结果

http://localhostAAA:1885

你可能感兴趣的:(Java,Web项目技术,java,配置文件,经验分享)