admin管理员组

文章数量:1568790

1.@Value注解读取方式

application.yml自定义配置

读取配置类

package com.ruoyimon.core.domain;

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

@Component
public class OpcserverConfig {


    @Value("${opcserver.ip}")
    private String ip;

    @Value("${opcserver.port}")
    private String port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

2.@ConfigurationProperties注解读取方式

读取配置类

package com.ruoyimon.core.domain;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "opcserver")
public class OpcserverConfig2 {


    private String ip;

    private String port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

读取指定文件

注意:1.在资源目录(resources)下创建2.@PropertySource不支持yml文件读取。

方式一:@PropertySource+@Value注解读取方式

package com.ruoyimon.core.domain;

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

@Component
@PropertySource(value = "opcconfig.properties")
public class OpcConfig {


    @Value("${opc.ip}")
    private String ip;

    @Value("${opc.port}")
    private String port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

方式二:@PropertySource+@ConfigurationProperties注解读取方式

package com.ruoyimon.core.domain;

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

@Component
@ConfigurationProperties(prefix = "opc")
@PropertySource(value = {"opcconfig.properties"})
public class OpcConfig2 {


    @Value("${opcs.ip}")
    private String ip;

    @Value("${opc.port}")
    private String port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

三.Environment直接读取配置

    @Autowired
    private Environment env;
    
   	public String getOpcIp(){
      return env.getProperty("opc.ip");
    }

本文标签: 几种自定义配置文件方式SpringBoot