前面的文章中有提到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 = {