- @SpringBootApplication
- @Configuration
- @Component/@Service
- @Resouce/@Autowired
- @Controller/@RestController
- @RequestMapping
- @Bean
@Resource/@Autowire/@Inject
Spring和Java-EE
- JavaEE是Sun公司提出的一套企业级的应用开发规范,规范包括:Servlet、JSP、JPA(ORM框架标准)、JSR-250(Java规范请求)等;JavaEE应用通常打包为war包。@Resource、@Inject就属于Java-EE规范,@Resource是2006年推出,@Inject在2009年由Google推出;
- Spring于2004发布第一版,起初就是为了对抗JavaEE的臃肿,也是为了脱离Java-EE。
Spring不会使用@Resource作为DI的注解,因为:
- @Autowired比@Resource更早;
- Spring不是建立在Java-EE规范中的,它兼容Java-EE,但不依赖Java-EE,既然不依赖,就不会只能使用@Resource
- Spring推荐使用构造函数注入来实现不可变对象,而@Resource不支持构造函数,仅支持字段和Setter方法;但是@Inject实际上可以等价于@Autowired;
- @Autowired可以和@Primary、@Profile、@Conditional等注解配合使用,实现更精细的 Bean 选择逻辑
什么情况下使用@Resource:
- 非Spring生态的服务端对象容器;
- 考虑底层容器的切换、移植,可能切换到非Spring容器;
实际上选择什么,还是取决于工程团队的技术生态。
@Mapper/@Repository
@Repository
需要额外配置Dao扫描地址;
@Mapper
=@Repository
+@MapperScan
@Component/@Bean/@Service/@Repository
@Component:用于将Java类标记为SpringBean,由Spring扫描注入到IOC容器,交由Spring管理;
@Bean:用于将Java方法返回的对象注入到IOC容器;
@Service:@Component的特化,没有额外功能,语义上更适用于业务代码;
@Repository:@Component的特化,通常用于DAO层,但是@Repository允许非受检异常转为Spring DataAccessException
@PostConstruct
- @PostConstruct在Bean初始化之前执行;
- 然后Bean进行初始化(initalizeBean)
- 如果在xml中配置了,就继续执行init-method方法(已经很少用了)
- init-method通过反射执行,不允许有入参;