美文网首页探索SpringJava基础Spring Boot
Spring常用注解@Autowired、@Qualifier

Spring常用注解@Autowired、@Qualifier

作者: Real_man | 来源:发表于2018-11-12 08:10 被阅读5次

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;

}

参考

相关文章

网友评论

    本文标题:Spring常用注解@Autowired、@Qualifier

    本文链接:https://www.haomeiwen.com/subject/dscqfqtx.html