相关注解
bean声明
- @componentScan
- @bean
- @compent
- @service
- @controller
- @configuration
bean组入:
@Autowired和@Qualifier
@Resource()
属性注入
- @Autowired
- @Value
- @PropertySource
- @ConfigurationProperty
属性组入示例
普通属性注入
@Data
public class Dog {
private String name;
private Integer age;
}
@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person {
private String name;
private Integer age;
private Boolean boss;
private Date birth;
private String[] jobs;
private List<String> lists;
private Map<String, String> maps;
private Dog dog;
}
application.yml文件
person:
name: name
age: 14
boss: false
birth: 2014/2/23
jobs: 12,23,34,545
lists:
- list
- set
- map
maps: [key1:value,key2:value,keg4:value]
dog:
name: x考古
age: 22
@ConfigurationProperties 使用相同前缀的配置属性 @Component 声明为bean,支持注入 若使用@EnableConfigurationProperties, 自动对使用@ConfigurationProperties的类声明bean
使用指定配置文件注入
@Component
@ConfigurationProperties(prefix = "school")
//加载指定配置文件,不支持yml文件读取
@PropertySource("classpath:person_info.properties")
@Data
public class School {
private String age;
private String name;
}
person_info.properties文件
school.name=test
school.age=44
@PropertySource 读取指定配置文件属性,不支持yml文件读取
静态属性注入
@Component
@ConfigurationProperties(prefix = "school2")
//加载指定配置文件,不支持yml文件读取
@PropertySource("classpath:person_info.properties")
public class School2 {
private static String age;
private static String name;
/**
* 支持静态属性注入,set方法设置为非静态
*
* @param age
*/
public void setAge(String age) {
School2.age = age;
}
public void setName(String name) {
School2.name = name;
}
public static String getName() {
return name;
}
public static String getAge() {
return age;
}
}
@Component
public class Person_static {
public static Integer age;
/**
* 非static方法,支持静态属性注入
*
* @param age
*/
@Value("${person.age}")
public void setAge(Integer age) {
Person_static.age = age;
}
public static Integer getAge() {
return age;
}
}
person_info.properties文件
school2.name=test2
school2.age=442
静态属性注入,把set方法设置为非静态即可