@Value方式
通过@Value(只能注入单个的属性信息),这个比较简单,只需要在@Value(“${key}”);
除了注入已经存在与yml中的变量以外,还可以注入一些默认值,保证在yml中没有编写属性的时候,程序依然可以运行。默认值为空:
1 2
| @Value("${spring.redis.global:}") private String global;
|
@ConfigurationProperties方式
在类上通过 @ConfigurationProperties(prefix = “report”),将yml中的多个属性对应到一个类的属性上。在类上加入@Component和@ConfigurationProperties注解即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Component @ConfigurationProperties(prefix = "urlconfig") public class UrlConfig { private String baseUrl=""; private String staticUrl=""; private String pipeline=""; private String pipelineConfig=""; private String pipelineTimeData=""; private String pipelineTimeDataBackups=""; private String station=""; private String stationConfig=""; private String stationTimeData=""; private String factory=""; private String getUserFreeSetting=""; private String setUserFreeSetting=""; private String drawConfig=""; private String getSimulationValue=""; private String getDbList=""; }
|
在使用@ConfigurationProperties 时,要注意需要在pom.xml中加入依赖。
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
|
否则 IDEA 中就会出现警告:
然后就可以使用@Autowired,在其他类中,自动注入UrlConfig类了,
3.注入对象数组
如果yml中定义了如下的对象数组,如何才能实现自动注入呢?
1 2 3 4
| databases: list: - {id: 1,name: 张三,age: 12} - {id: 2,name: 李四,age: 13}
|
(1) 首先定义内部对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class Databases {
public Databases() { super(); }
private String id; private String name; private String age;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAge() { return age; }
public void setAge(String age) { this.age = age; } }
|
(2) 使用@ConfigurationProperties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration;
import java.util.ArrayList; import java.util.List;
@Configuration @ConfigurationProperties(prefix = "databases",ignoreUnknownFields = false) public class DatabasesList { private List<Databases> list=new ArrayList<Databases>();
public DatabasesList() { super(); }
public DatabasesList(List<Databases> list) { super(); this.list = list; }
public List<Databases> getList() { return list; }
public void setList(List<Databases> list) { this.list = list; } }
|
(3) 使用DatabasesList
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Controller @RequestMapping("/") public class LinkCtl {
@Autowired private DatabasesList databasesList;
@RequestMapping("/") public String index(ModelMap map){ System.out.println(databasesList.getList()); map.put("name","sdf"); return "index"; } }
|