Spring常用注解@Autowired、@Qualifier
Java语言从JDK1.5开始支持注解,Spring从2.5版本后开始采用注解,在此之前,我们都是通过XML来配置Spring,到现在Spring内部有很多注解,这些注解给我们的开发提供了很多的便利。
这篇文章,我们整理下Spring框架的常用注解
核心注解
@Autowired
这个注解可以用于属性,setter方法,还有构造器上,这个注解用于注入依赖的对象。当你再一个属性上加上@Autowired注解,有时可能要指定一些额外的值,Spring然后会自动的将值赋给这个属性。
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autowired { /** * Declares whether the annotated dependency is required. * <p>Defaults to {@code true}. */ boolean required() default true; }
@Qualifier
这个注解通常和@Autowired一起使用,当你想对注入的过程做更多的控制,@Qualifier可以帮助你指定做更详细配置。一般在两个或者多个bean是相同的类型,spring在注入的时候会出现混乱。
比如:有个接口叫做HelloInterface
,然后有两个bean都实现了HelloInterface接口。
@Component public class Bean1 implements HelloInterface { // } @Component public class Bean2 implements HelloInterface { // }
如果我们只使用@Autowired注解,Spring就不知道到底要注入哪一个bean。解决办法就是加上@Qualifier注解
@Component public class BeanA { @Autowired @Qualifier("bean2") private HelloInterface dependency; ...
@Configuration
这个注解一般用在类上面,加上@Configuration的类可以想象为一个spring的xml配置文件,只不过这次是使用基于java 代码的配置。
标记一个类为spring的配置
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Configurable { /** * The name of the bean definition that serves as the configuration template. */ String value() default ""; /** * Are dependencies to be injected via autowiring? */ Autowire autowire() default Autowire.NO; /** * Is dependency checking to be performed for configured objects? */ boolean dependencyCheck() default false; /** * Are dependencies to be injected prior to the construction of an object? */ boolean preConstruction() default false; }
参考
原文地址:https://www.jianshu.com/p/38d0657abb00
相关推荐
-
SpringMVC 异常处理. Java框架
2019-8-16
-
docker指令学习记录 Java框架
2018-12-7
-
Spring Boot 的 10 个核心模块 Java框架
2019-3-4
-
SpringBoot开发案例之mail中文附件乱码 Java框架
2019-3-13
-
Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例 Java框架
2019-9-16
-
详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(下) Java框架
2019-10-7
-
Spring核心——数据校验 Java框架
2020-7-4
-
Spring中引入增强(IntroductionAdvice)的底层实现理 Java框架
2020-6-8
-
spring源码分析 contextConfigLocation属性的位置 Java框架
2019-9-11
-
SpringApplication对象是如何构建的? SpringBoot源码(八) Java框架
2020-6-11