一、@Value注解读取yml文件配置
1.在application.yml文件中配置信息
aliyun:
host: 110.121.111.111
2.读取配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class YmlTest {
@Value("${aliyun.host}")
private String host;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
3、使用
@Autowired
YmlTest test;
@Test
void test1(){
String host = test.getHost();
System.out.println(host);
}
}
二、使用@ConfigurationProperties注解读取配置
1、pom.xml引入configuration依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、配置application.yml
springcss:
proints:
order1: test1
order2: test2
order3: test3
3、读取配置
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "springcss.proints")
public class OrderAddress {
private String order1;
private String order2;
private String order3;
public String getOrder1() {
return order1;
}
public void setOrder1(String order1) {
this.order1 = order1;
}
public String getOrder2() {
return order2;
}
public void setOrder2(String order2) {
this.order2 = order2;
}
public String getOrder3() {
return order3;
}
public void setOrder3(String order3) {
this.order3 = order3;
}
}
@Autowired
OrderAddress orderAddress;
@Test
void contextLoads() {
String order1 = orderAddress.getOrder1();
System.out.println(order1);
}
三、读取properties资源文件
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;
@Component
@PropertySources({
@PropertySource("classpath:config/mq.properties"),
@PropertySource("classpath:config/redis.properties")
})
public class OrderAddress {
}
mq.properties
## 防止中文乱码
spring.http.encoding.enabled = true
host = jdbc:mysql://localhost:3306/DatebaseName(数据库))
3、读取配置
@Autowired
Environment environment;
@Test
void contextLoads() {
String host = environment.getProperty("host");
System.out.println(host);
}
附上Demo目录