美文网首页工作生活
Spring的@AutoWired注释

Spring的@AutoWired注释

作者: 安在成丶 | 来源:发表于2019-07-02 17:00 被阅读0次

Spring @Autowired最终是根据类型来查找和装配元素的。

@Autowired 注释通过执行“byType”自动连接的形式,用来自动装配指定的字段或者方法,注入属性值。

根据属性类型,或者是方法参数类型,通过适配Bean中class的类型,相同类型,即完成自动装配,依赖注入。

通过这样的方式,可以减少或者消除属性或者构造器参数的设置。

@AutoWired可以应用在Setter方法属性以及构造函数中。

Student.java 文件内容如下:

public classTextEditor{

@Autowired  

  private SpellChecker spellChecker;//应用在属性上,根据属性类型自动装配

  @Autowired  

 public void setSpellChecker( SpellChecker spellChecker ){//应用在Setter方法上,根据参数类型自动装配

      this.spellChecker = spellChecker;

  }

  public SpellChecker getSpellChecker( ){

      return spellChecker;

  }

@Autowired 

 public TextEditor (SpellChecker spellChecker){//应用在构造函数上,根据参数类型自动装配

      System.out.println("Inside TextEditor constructor." );

      this.spellChecker = spellChecker;

  }

  public void spellCheck(){

      spellChecker.checkSpelling();

  }

}

ApplicationContext.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:annotation-config/>

  <!-- Definition for textEditor bean -->

  <bean id="textEditor" class="com.tutorialspoint.TextEditor">

  </bean>

  <!-- Definition for spellChecker bean -->

  <bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">

  </bean>

</beans>


当在 setter 方法中使用的 @Autowired 注释,它会在方法中视图执行 byType 自动连接,根据参数类型,自动适配Bean中的class的类型

当在属性中使用@Autowired 的时候,根据属性类型,Spring 会将这些传递过来的值或者引用自动分配给那些属性。

当构造函数配置了 @Autowired, 当创建 bean 时,即使在 XML 文件中没有使用 元素配置 bean ,构造函数也会被自动连接。

如果配置了@Autowired注解,默认情况下意味着必须注入依赖,就跟@Required的校验一样的属性,如果不注入相关依赖,就会抛出异常

可以通过 @Autowired 的 (required=false) 选项关闭默认行为,不用必须注入依赖。

@Autowired(required=false)

  publicvoidsetAge(Integer age)

相关文章

网友评论

    本文标题:Spring的@AutoWired注释

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