您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

Spring Boot最核心的3个注解的介绍(附代码)

2024/3/28 19:44:25发布4次查看
本篇文章给大家带来的内容是关于spring boot最核心的3个注解的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
最近面试一些 java 开发者,他们其中有些在公司实际用过 spring boot, 有些是自己兴趣爱好在业余自己学习过。然而,当我问他们 spring boot 最核心的 3 个注解是什么,令我失望的是鲜有人能答上来,这样你能说你对 spring boot 很了解吗?这可能还会给你减分!
spring boot 核心注解讲解
spring boot 最大的特点是无需 xml 配置文件,能自动扫描包路径装载并注入对象,并能做到根据 classpath 下的 jar 包自动配置。
所以 spring boot 最核心的 3 个注解就是:
1、@configuration
org.springframework.context.annotation.configuration
这是 spring 3.0 添加的一个注解,用来代替 applicationcontext.xml 配置文件,所有这个配置文件里面能做到的事情都可以通过这个注解所在类来进行注册。
下面几个相关注解也是非常重要的!
@bean
用来代替 xml 配置文件里面的 <bean ...> 配置。
@importresource
如果有些通过类的注册方式配置不了的,可以通过这个注解引入额外的 xml 配置文件,有些老的配置文件无法通过 @configuration 方式配置的非常管用。
@import
用来引入额外的一个或者多个 @configuration 修饰的配置文件类。
@springbootconfiguration
这个注解就是 @configuration 注解的变体,只是用来修饰是 spring boot 配置而已,或者可利于 spring boot 后续的扩展,源码如下。
@target(elementtype.type)@retention(retentionpolicy.runtime)@documented@configurationpublic @interface springbootconfiguration {}
2、@componentscan
org.springframework.context.annotation.componentscan
这是 spring 3.1 添加的一个注解,用来代替配置文件中的 component-scan 配置,开启组件扫描,即自动扫描包路径下的 @component 注解进行注册 bean 实例到 context 中。
另外,@componentscans 是可重复注解,即可以配置多个,用来配置注册不同的子包。
3、@enableautoconfiguration
org.springframework.boot.autoconfigure.enableautoconfiguration
看全路径就知道,这是自 spring boot 诞生时添加的注解,用来提供自动配置,上面的两个都是 spring-context 包下的,不属于 spring boot,所以 spring 3.0 之后的去 xml 配置方式已经为 spring boot 埋下了伏笔!
自动配置更多详细使用及实战可以看这篇文章《spring boot自动配置原理、实战》。
最后的彩蛋spring boot 最核心的 3 个注解介绍完了,大家可能会有疑问,为什么最主要的注解 @springbootapplication 不在其中?
留给大家的彩蛋,其实这个 @springbootapplication 注解就包含了以上 3 个主要注解,平时没有自定义配置的需求,则使用 @springbootapplication 注解完全就可以了!
让我们来看下 @springbootapplication 注解的源码,一切明了!
@target(elementtype.type)@retention(retentionpolicy.runtime)@documented@inherited@springbootconfiguration@enableautoconfiguration@componentscan(excludefilters = {        @filter(type = filtertype.custom, classes = typeexcludefilter.class),        @filter(type = filtertype.custom, classes = autoconfigurationexcludefilter.class) })public @interface springbootapplication {    ...}
以上就是spring boot最核心的3个注解的介绍(附代码)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录