springboot2.2.X手册:36个注解详细解析,一目了然

2024-06-18 01:48

本文主要是介绍springboot2.2.X手册:36个注解详细解析,一目了然,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

@Component

@Service

@Repository

@Controller

@Autowired

@Inject

@Resource

@Configuration

@Bean

@ComponentScan

@WishlyConfiguration

@Aspect

@After

@Before

@Around

@PointCut

@Scope

@Value

@PropertySource

@Profile

@Conditional

@EnableAsync

@Async

@EnableScheduling

@Scheduled

@EnableJpaRepositories

@EnableTransactionManagement

@EnableCaching

@Cacheable

@RequestMapping

@ResponseBody

@RequestBody

@PathVariable

@RestController

@ControllerAdvice

@ExceptionHandler


 

@Component

作用及范围:把对象加载到spring容器中,最基础的存在,很多的注解都是继承它的,只有一个属性值,默认值是“”,

例子或源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {String value() default "";}

@Service

作用及范围:一般用于service层的注解,继承了Component组件,本质上一样,方便做业务范围区分而已。

例子或源码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {@AliasFor(annotation = Component.class)String value() default "";}

 

@Repository

作用及范围:作用于dao层的注解,很多经常用JPA的同学都清楚这个东西,与Service本质上一样,业务领域上区别而已

例子或源码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {@AliasFor(annotation = Component.class)String value() default "";}

 

 

@Controller

作用及范围:作用在控制器上的注解,与Service一样,业务领域区分

例子或源码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {@AliasFor(annotation = Component.class)String value() default "";}

@Autowired

作用及范围:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,其实就是获取容器中的对象

注意事项:

在使用@Autowired时,首先在容器中查询对应类型的bean

如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据

如果查询的结果不止一个,那么@Autowired会根据名称来查找。

如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false

例子或源码:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {boolean required() default true;}

@Inject

作用及范围:它是JSR330 (Dependency Injection for Java)中的规范,需要导入javax.inject.Inject;实现注入,根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Named,可以作用在变量、setter方法、构造函数上。很少用

例子或源码:

@Inject
public Message(Header header, Content content)
{this.headr = header;this.content = content;
}
public class Messager
{@Injectprivate Message message;
}

 

 

@Resource

作用及范围:它是JSR250规范的实现,也是需要导入javax.annotation实现注入,根据名称进行自动装配的,一般会指定一个name属性,可以作用在变量、setter方法上。

例子或源码:

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {String name() default "";String lookup() default "";Class<?> type() default java.lang.Object.class;enum AuthenticationType {CONTAINER,APPLICATION}AuthenticationType authenticationType() default AuthenticationType.CONTAINER;boolean shareable() default true;String mappedName() default "";String description() default "";
}

@Configuration

作用及范围:从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,同样AliasFor最原始的注解Component

例子或源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {@AliasFor(annotation = Component.class)String value() default "";boolean proxyBeanMethods() default true;}

@Bean

作用及范围:作用于方法上,产生一个对象,然后这个对象交给Spring管理,在进行初始化的过程中,只会产生并调用一次,如果容器管理一个或者多个bean,这些bean都需要在Configuration注解下进行创建,在一个方法上使用Bean注解就表明这个方法需要交给Spring进行管理。

例子或源码:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {@AliasFor("name")String[] value() default {};@AliasFor("value")String[] name() default {};Autowire autowire() default Autowire.NO;String initMethod() default "";String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;}

@ComponentScan

作用及范围:扫描当前类下面的所有对象,为什么说Component是最基础的东西,就是要给这个注解扫描,非常巧妙的设计,可以扫描多个包。

例子或源码:

@ComponentScan(“com.abc.aaa”)
@SpringBootApplication
public class SpringbootApplication {
@ComponentScan({"com.abc.bbb","com.abc.aaa"})
@SpringBootApplication
public class SpringbootApplication {

 

 

@WishlyConfiguration

作用及范围:这个是ConfigurationComponentScan的组合注解,可以替代这两个注解,目前非常少用。

例子或源码:没用过

@Aspect

作用及范围:切面注解,切面编程经常用到的,可以做日志

例子或源码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Aspect {public String value() default "";
}

@After

作用及范围:配置Aspect做切面使用,在方法执行之后执行(方法上)

例子或源码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {String value();String argNames() default "";
}

@Before

作用及范围:配置Aspect做切面使用,在方法执行之前执行(方法上)

例子或源码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {String value();String argNames() default "";}

@Around

作用及范围:配置Aspect做切面使用,在方法执行之前与之后执行(方法上)

例子或源码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Around {String value();String argNames() default "";}

@PointCut

作用及范围:配置Aspect做切面使用,声明切点

例子或源码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Pointcut {String value() default "";String argNames() default "";
}

 

 

@Scope

作用及范围:Singleton (单例,一个Spring容器中只有一个bean实例,默认模式),

Protetype (每次调用新建一个bean),

Request (web项目中,给每个http request新建一个bean),

Session (web项目中,给每个http session新建一个bean),

GlobalSession(给每一个 global http session新建一个Bean实例)

例子或源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {@AliasFor("scopeName")String value() default "";@AliasFor("value")String scopeName() default "";ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;}

@Value

作用及范围:将外部的值动态注入到Bean中,使用的情况有:

  1. 注入普通字符串
  2. 注入操作系统属性
  3. 注入表达式结果
  4. 注入其他Bean属性:注入beanInject对象的属性another
  5. 注入文件资源
  6. 注入URL资源

例子或源码:

   @Value("normal")private String normal; // 注入普通字符串@Value("#{systemProperties['os.name']}")private String systemPropertiesName; // 注入操作系统属性@Value("#{ T(java.lang.Math).random() * 100.0 }")private double randomNumber; //注入表达式结果@Value("#{beanInject.another}")private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面@Value("classpath:com/hry/spring/configinject/config.txt")private Resource resourceFile; // 注入文件资源@Value("http://www.baidu.com")private Resource testUrl; // 注入URL资源

 

 

@PropertySource

作用及范围:加载指定的配置文件

例子或源码:

@PropertySource(value = {"classpath:test.properties"})
@Component
@ConfigurationProperties(prefix = "test")
public class Test {private Integer id;private String lastName;
}

@Profile

作用及范围:根据不同环境加载bean对象

例子或源码:

@PropertySource("classpath:/user.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{@Profile("test")@Bean("testUser")public User testUser()  {User a =new User();return a;}@Profile("dev")@Bean("devUser")public User devUser()  {User a =new User();return a;}}

@Conditional

作用及范围:是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean

例子或源码:

@Configuration
public class BeanConfig {//只有一个类时,大括号可以省略//如果WindowsCondition的实现方法返回true,则注入这个bean    @Conditional({WindowsCondition.class})@Bean(name = "bill")public Window window(){return new Window();}//如果LinuxCondition的实现方法返回true,则注入这个bean@Conditional({LinuxCondition.class})@Bean("linux")public Linex linux(){return new Linex();}
}

 

 

@EnableAsync

作用及范围:启动异步,与Async配合使用

例子或源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {Class<? extends Annotation> annotation() default Annotation.class;boolean proxyTargetClass() default false;AdviceMode mode() default AdviceMode.PROXY;int order() default Ordered.LOWEST_PRECEDENCE;}

@Async

作用及范围:异步注解,需配合EnableAsync使用,使用后,方法变成异步方法

例子或源码:

@Component
public class TreadTasks {@Asyncpublic void startMyTreadTask() {System.out.println("this is my async task");}
}

@EnableScheduling

作用及范围:定时任务注解扫描器,会扫描包体下的所有定时任务

例子或源码:

@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class, args);}
}

 

 

@Scheduled

作用及范围:定时任务控制器

例子或源码:

 

springboot2.2.X手册:36个注解详细解析,一目了然

 

@Scheduled(cron = "0 0 2 * * ?") 

@EnableJpaRepositories

作用及范围:开启对SpringData JPA Repository的支持

例子或源码:

@EnableJpaRepositories({"com.cshtong.sample.repository", "com.cshtong.tower.repository"})

@EnableTransactionManagement

作用及范围:开启注解式事务的支持

例子或源码:最常见的东西,不做讲解了

@EnableTransactionManagement // 启注解事务管理
@SpringBootApplication
public class ProfiledemoApplication {public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}

 

 

@EnableCaching

作用及范围:开启注解式的缓存支持

例子或源码:

@Configuration
@EnableCaching
public class CachingConfig {@Beanpublic CacheManager cacheManager() {SimpleCacheManager cacheManager = new SimpleCacheManager();cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));return cacheManager;}
}

@Cacheable

作用及范围:把信息放到存储中去

例子或源码:

@Cacheable(value = { "sampleCache","sampleCache2" },key="targetClass.getName()+'.'+methodName+'.'+#id")public String getUser(int id) {if (id == 1) {return "1";} else {return "2";}}

 

@RequestMapping

作用及范围:注解来将请求URL映射到整个类上,或某个特定的方法上

例子或源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {String name() default "";@AliasFor("path")String[] value() default {};@AliasFor("value")String[] path() default {};RequestMethod[] method() default {};String[] params() default {};String[] headers() default {};String[] consumes() default {};String[] produces() default {};}

 

 

@ResponseBody

作用及范围:将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据

例子或源码:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {}

@RequestBody

作用及范围:用来接收前端传递给后端的json字符串中的数据(请求体中的数据的)

例子或源码:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {/*** 默认是必须的*/boolean required() default true;}

@PathVariable

作用及范围:接收请求路径中占位符的值

例子或源码:

@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/user//1/james

@RestController

作用及范围:等同于@Controller + @ResponseBody

例子或源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {@AliasFor(annotation = Controller.class)String value() default "";}

 

 

@ControllerAdvice

作用及范围:全局异常处理;全局数据绑定;全局数据预处理

例子或源码:

@ControllerAdvice
public class MyGlobalExceptionHandler {@ExceptionHandler(Exception.class)public ModelAndView customException(Exception e) {ModelAndView mv = new ModelAndView();mv.addObject("message", e.getMessage());mv.setViewName("error");return mv;}
}@ControllerAdvice
public class MyGlobalExceptionHandler {@ModelAttribute(name = "md")public Map<String,Object> mydata() {HashMap<String, Object> map = new HashMap<>();map.put("gender", "女");return map;}
}

@ExceptionHandler

作用及范围:用于处理controller层面的异常

例子或源码:

 @ExceptionHandler({RuntimeException.class})public ModelAndView fix(Exception ex){System.out.println("aaaa");return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));}

 

这篇关于springboot2.2.X手册:36个注解详细解析,一目了然的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1070966

相关文章

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Java 关键字transient与注解@Transient的区别用途解析

《Java关键字transient与注解@Transient的区别用途解析》在Java中,transient是一个关键字,用于声明一个字段不会被序列化,这篇文章给大家介绍了Java关键字transi... 在Java中,transient 是一个关键字,用于声明一个字段不会被序列化。当一个对象被序列化时,被

Logback在SpringBoot中的详细配置教程

《Logback在SpringBoot中的详细配置教程》SpringBoot默认会加载classpath下的logback-spring.xml(推荐)或logback.xml作为Logback的配置... 目录1. Logback 配置文件2. 基础配置示例3. 关键配置项说明Appender(日志输出器

Java JSQLParser解析SQL的使用指南

《JavaJSQLParser解析SQL的使用指南》JSQLParser是一个Java语言的SQL语句解析工具,可以将SQL语句解析成为Java类的层次结构,还支持改写SQL,下面我们就来看看它的具... 目录一、引言二、jsQLParser常见类2.1 Class Diagram2.2 Statement

python进行while遍历的常见错误解析

《python进行while遍历的常见错误解析》在Python中选择合适的遍历方式需要综合考虑可读性、性能和具体需求,本文就来和大家讲解一下python中while遍历常见错误以及所有遍历方法的优缺点... 目录一、超出数组范围问题分析错误复现解决方法关键区别二、continue使用问题分析正确写法关键点三

Spring Cache注解@Cacheable的九个属性详解

《SpringCache注解@Cacheable的九个属性详解》在@Cacheable注解的使用中,共有9个属性供我们来使用,这9个属性分别是:value、cacheNames、key、key... 目录1.value/cacheNames 属性2.key属性3.keyGeneratjavascriptor

使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案

《使用@Cacheable注解Redis时Redis宕机或其他原因连不上继续调用原方法的解决方案》在SpringBoot应用中,我们经常使用​​@Cacheable​​注解来缓存数据,以提高应用的性能... 目录@Cacheable注解Redis时,Redis宕机或其他原因连不上,继续调用原方法的解决方案1

使用Java实现Navicat密码的加密与解密的代码解析

《使用Java实现Navicat密码的加密与解密的代码解析》:本文主要介绍使用Java实现Navicat密码的加密与解密,通过本文,我们了解了如何利用Java语言实现对Navicat保存的数据库密... 目录一、背景介绍二、环境准备三、代码解析四、核心代码展示五、总结在日常开发过程中,我们有时需要处理各种软

Java内存区域与内存溢出异常的详细探讨

《Java内存区域与内存溢出异常的详细探讨》:本文主要介绍Java内存区域与内存溢出异常的相关资料,分析异常原因并提供解决策略,如参数调整、代码优化等,帮助开发者排查内存问题,需要的朋友可以参考下... 目录一、引言二、Java 运行时数据区域(一)程序计数器(二)Java 虚拟机栈(三)本地方法栈(四)J