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;

}

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容