当前位置:   article > 正文

SpringBoot配置文件的属性注入_springboot 像xml 那样配置依赖注入

springboot 像xml 那样配置依赖注入

spring中配置文件的属性注入都是@Value("${}")这种,springboot中提供了另一种(可以说是简化吧)。

1.pom.xml中引入:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>

亲测:不引入也可(可能是其他依赖包中已引入)

2.application.properties中编写配置:

  1. mytest.name=haha
  2. mytest.password=123456
  3. mytest.age=26

3.配置文件的属性注入类:

  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.stereotype.Component;
  3. /**
  4. * @description:
  5. * @author:
  6. * @create: 2019-02-12 09:54
  7. **/
  8. @Component
  9. @ConfigurationProperties(prefix = "mytest")//prefix指定了配置文件属性的前缀为mytest,并且按照属性名进行自动匹配,例如:mytest.name属性值会自动setter到private String name域中。
  10. public class EntityTest {
  11. private String name;
  12. private String password;
  13. private Integer age;
  14. @Override
  15. public String toString() {
  16. return "EntityTest{" +
  17. "name='" + name + '\'' +
  18. ", password='" + password + '\'' +
  19. ", age=" + age +
  20. '}';
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public String getPassword() {
  29. return password;
  30. }
  31. public void setPassword(String password) {
  32. this.password = password;
  33. }
  34. public Integer getAge() {
  35. return age;
  36. }
  37. public void setAge(Integer age) {
  38. this.age = age;
  39. }
  40. }

注意:setter方法是必须的!

4.启动类测试:

  1. @org.springframework.boot.autoconfigure.SpringBootApplication//@EnableAutoConfiguration @ComponentScan
  2. public class SpringBootApplication implements CommandLineRunner {
  3. public static void main(String[] args) {
  4. SpringApplication.run(SpringBootApplication.class, args);
  5. }
  6. @Autowired
  7. EntityTest entityTest;
  8. @Override
  9. public void run(String... args) throws Exception {
  10. System.out.println(entityTest);
  11. }
  12. }

运行结果:EntityTest{name='haha', password='123456', age=26}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/90499
推荐阅读
相关标签
  

闽ICP备14008679号