前面的文章中有提到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
参考:https://www.cnblogs.com/toutou/p/9907753.html