说到 SpringBoot,需要提一下:
一、Spring的历史版本与配置方式
1. Spring 1.x
完全是 xml 的配置。
缺点:随着项目的扩大,xml越来越多,而且需要对xml分类。
2. Spring 2.x
在 JDK 1.5 更新的时代,可以使用注解。Spring 2.X 开始使用注解。
那么问题是:使用xml?还是使用注解?
得出最佳实践:
应用的基本配置用xml,业务用注解。
3. Spring 3.x
推荐使用 java 代码的配置注解,取代 xml
@Configuration, @Bean
4. Spring 4.x
SpringBoot 诞生
二、Spring 4.x @Component 与 @Bean 的区别
https://stackoverflow.com/questions/10604298/spring-component-versus-bean
@Component 是加在类上;
@Bean 是加在方法上;而且可以手动指定生成哪个类的具体实例。
三、Spring 4.x @Resource 与 @Autowired 的区别
https://stackoverflow.com/questions/4093504/resource-vs-autowired
@Resource是 By Name 来匹配的,没有找到对应的名字时则调用 @Autowired。
名字可以用 @Resource(name="blah")属性指定,缺省则使用变量名。
@Autowired是 By Type 来匹配的。常与 @Autowired @Qualifier("blah") 结合使用。
依赖注入的第三种方式:
@Qualifier @Retention(RUNTIME) public @interface YourQualifier {}
@YourQualifier @Component public class SomeBean implements Foo { .. }
And then
@Inject @YourQualifier private Foo foo;
@RESOURCE VS @AUTOWIRED VS @INJECT
ANNOTATION | PACKAGE | SOURCE |
@Resource | javax.annotation | Java |
@Inject | javax.inject | Java |
@Qualifier | javax.inject | Java |
@Autowired | org.springframework.bean.factory | Spring |
@Resource @Qualifier("person") private Party party; @Autowired @Qualifier("person") private Party party; @Inject @Qualifier("person") private Party party;
https://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/
四、Spring 4.x @PropertySources 与 @PropertySource
https://www.mkyong.com/spring/spring-propertysources-example/
Some enhancements on Spring 4.
- Introduces new @PropertySources to support Java 8 and better way to include multiple properties files.
@Configuration @PropertySources({ @PropertySource("classpath:config.properties"), @PropertySource("classpath:db.properties") }) public class AppConfig { //... }
- Allow @PropertySource to ignore the not found properties file.
@Configuration @PropertySource("classpath:missing.properties") public class AppConfig { //... }
If missing.properties is not found, the system is unable to start and throws FileNotFoundException
Caused by: java.io.FileNotFoundException:
class path resource [missiong.properties] cannot be opened because it does not exist
In Spring 4, you can use ignoreResourceNotFound to ignore the not found properties file
@Configuration @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true) public class AppConfig { //... } @PropertySources({ @PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true), @PropertySource("classpath:config.properties") })
-