1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-configuration-processor</artifactId>
<optional> true </optional>
</dependency>
2.在resources下建一个config包(包名随意),在包里建一个properties文件(文件名随意)(我在这里尝试用yml文件配置但是失败了)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a760663912e6bf55e21d407023020c35.png)
3.在配置文件写入内容
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0b881f441bec5074c7c4a7229da2ce0e.png)
login.username=12222
login.test=12222
4.写一个实体类,属性和配置文件对应
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e3e9db4ef188c3ef660c0c68f4bdf513.png)
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration
@ConfigurationProperties(prefix = "login",ignoreUnknownFields = false)
@PropertySource("classpath:config/login.properties")
@Data
@Component
public class LoginYml {
private String username;
private String test;
}
5.测试
@RestController
@EnableConfigurationProperties(LoginYml.class)
public class TestController {
@Autowired
LoginYml loginYml;
@GetMapping("/test")
public String test(){
return loginYml.getUsername();
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0ba1aebb2ca762bc2af6c0f445bdbe11.png)