1.添加pom依赖
1 2 3 4 5 | <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional> true </optional> </dependency> |
2.application.yml文件中添加需要配置的属性,注意缩进
1 2 3 4 5 | Myyml: username: cs password: 123456 url: jdbc:mysql: //localhost:3306/test driver: com.mysql.jdbc.Driver |
3.新建一个类,@Component注解表明是组件,可被自动发现,@ConfigurationProperties注解之前是location属性表明配置文件位置,prefix表示读取的配置信息的前缀,但新版本中废除了location属性(网上说是1.5.2之后),故只写前缀,默认读取application.yml中数据。重点!!一定要在这个类中写getter和setter,否则配置中的属性值无法自动注入
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | package com.cs.background.util; import lombok.ToString; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @ConfigurationProperties (prefix = "Myyml" ) public class User{ //数据库连接相关 private String url; private String driver; private String username; private String password; public String getUrl() { return url; } public void setUrl(String url) { this .url = url; } public String getDriver() { return driver; } public void setDriver(String driver) { this .driver = driver; } public String getUsername() { return username; } public void setUsername(String username) { this .username = username; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } } |
4.Controller类中执行自动注入,获取属性
1 2 3 4 5 | //自动注入 @Autowired private User user;<br> //方法体内获取属性值 String url=user.getUrl();<br>System.out.print(url); |
5.启动springboot入口类,调用对应controller对应的方法,控制台打印获取的值。