相关注解

bean声明

  • @componentScan
  • @bean
  • @compent
  • @service
  • @controller
  • @configuration

bean组入:

@Autowired和@Qualifier
image.png
@Resource()

属性注入

  • @Autowired
  • @Value
  • @PropertySource
  • @ConfigurationProperty

属性组入示例

普通属性注入

  1. @Data
  2. public class Dog {
  3. private String name;
  4. private Integer age;
  5. }
  6. @ConfigurationProperties(prefix = "person")
  7. @Component
  8. @Data
  9. public class Person {
  10. private String name;
  11. private Integer age;
  12. private Boolean boss;
  13. private Date birth;
  14. private String[] jobs;
  15. private List<String> lists;
  16. private Map<String, String> maps;
  17. private Dog dog;
  18. }

application.yml文件

  1. person:
  2. name: name
  3. age: 14
  4. boss: false
  5. birth: 2014/2/23
  6. jobs: 12,23,34,545
  7. lists:
  8. - list
  9. - set
  10. - map
  11. maps: [key1:value,key2:value,keg4:value]
  12. dog:
  13. name: x考古
  14. age: 22

@ConfigurationProperties 使用相同前缀的配置属性 @Component 声明为bean,支持注入 若使用@EnableConfigurationProperties, 自动对使用@ConfigurationProperties的类声明bean

使用指定配置文件注入

  1. @Component
  2. @ConfigurationProperties(prefix = "school")
  3. //加载指定配置文件,不支持yml文件读取
  4. @PropertySource("classpath:person_info.properties")
  5. @Data
  6. public class School {
  7. private String age;
  8. private String name;
  9. }

person_info.properties文件

  1. school.name=test
  2. school.age=44

@PropertySource 读取指定配置文件属性,不支持yml文件读取

静态属性注入

  1. @Component
  2. @ConfigurationProperties(prefix = "school2")
  3. //加载指定配置文件,不支持yml文件读取
  4. @PropertySource("classpath:person_info.properties")
  5. public class School2 {
  6. private static String age;
  7. private static String name;
  8. /**
  9. * 支持静态属性注入,set方法设置为非静态
  10. *
  11. * @param age
  12. */
  13. public void setAge(String age) {
  14. School2.age = age;
  15. }
  16. public void setName(String name) {
  17. School2.name = name;
  18. }
  19. public static String getName() {
  20. return name;
  21. }
  22. public static String getAge() {
  23. return age;
  24. }
  25. }
  26. @Component
  27. public class Person_static {
  28. public static Integer age;
  29. /**
  30. * 非static方法,支持静态属性注入
  31. *
  32. * @param age
  33. */
  34. @Value("${person.age}")
  35. public void setAge(Integer age) {
  36. Person_static.age = age;
  37. }
  38. public static Integer getAge() {
  39. return age;
  40. }
  41. }

person_info.properties文件

  1. school2.name=test2
  2. school2.age=442

静态属性注入,把set方法设置为非静态即可