1.@Value annotation reading method
application.yml custom configuration
reading configuration class
package com.ruoyi.common.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 annotation reading method
Read configuration class
package com.ruoyi.common.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;
}
}
Read the specified file
Note: 1. Created under the resource directory (resources) 2. @PropertySource does not support yml file reading.
Method 1: @PropertySource+@Value annotation reading method
package com.ruoyi.common.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;
}
}
Method 2: @PropertySource+@ConfigurationProperties annotation reading method
package com.ruoyi.common.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;
}
}
3. Environment reads configuration directly
@Autowired
private Environment env;
public String getOpcIp(){
return env.getProperty("opc.ip");
}