前面的文章中有提到Spring中bean的配置方式有三種:基於xml的配置、基於註解的配置和基於java的配置。而SpringBoot提倡基於Java的配置。
其常用的配置有@Value、@Import、@ImportResource、@PropertySource
@Value
通過@Value可以將外部的值動態注入到Bean中。
比如application.properties中添加屬性:
domain.name=testxxx
怎麼引用?
@Value("${domain.name}")
private String domainName; // 注入application.properties的配置屬性
@Import
在應用中,如果沒有把某個類注入到IOC容器中,但是需要獲取該類對應的bean,可以用到@Import註解,將指定的類實例注入到Spring IOC Container中。
比如有一個類:
public class Dog {
}
這個類既沒有作爲bean被聲明在xml,也沒有添加任何註解。
怎麼獲取這個類的bean?啓動類中加入@Import({Dog.class}),運行下面的代碼,可以正常運行。
@ComponentScan(basePackages = {"com.example.demo"})
@Import({Dog.class})
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//SpringApplication.run(DemoApplication.class, args);
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
System.out.println(context.getBean(Dog.class));
context.close();
}
}
@ImportResource
Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上.
@ImportResource(locations = {"classpath:dubbo.xml"})
public class RdsapiExtPgsqlApplication {
public static void main(String[] args) {
SpringApplication.run(RdsapiExtPgsqlApplication.class, args);
}
}
@PropertySource
前面提到@Value可以從全局配置文件application.properties或者application.xml中取值,然後爲需要的屬性賦值。當應用比較大的時候,如果所有的內容都保存在一個配置文件中,就會顯得比較臃腫,同時也不太好理解和維護。此時可以將一個文件拆分爲多個,使用@PropertySource註解加載指定的配置文件。
示例:
Person.java
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public boolean isBoss() {
return isBoss;
}
public void setBoss(boolean boss) {
isBoss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
private Integer age;
private boolean isBoss;
private Date birth;
}
person.properties
person.lastName=Jack
person.age=18
person.birth=2018/12/9
person.boss=true
啓動類DemoApplication.java:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//SpringApplication.run(DemoApplication.class, args);
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
Person ss = (Person)context.getBean(Person.class);
System.out.println(ss.getLastName());
System.out.println(ss.getAge());
System.out.println(ss.getBirth());
System.out.println(ss.isBoss());
context.close();
}
}
output:
Jack
18
Sun Dec 09 00:00:00 CST 2018
true