Spring @Autowired Annotation

Il @Autowiredl'annotazione fornisce un controllo più dettagliato su dove e come eseguire il cablaggio automatico. L'annotazione @Autowired può essere utilizzata per autowire il bean sul metodo setter proprio come l'annotazione @Required, il costruttore, una proprietà o metodi con nomi arbitrari e / o più argomenti.

@Autowired sui metodi Setter

Puoi usare @Autowiredannotazione sui metodi setter per eliminare l'elemento <property> nel file di configurazione XML. Quando Spring trova un'annotazione @Autowired usata con i metodi setter, prova a eseguirebyType autowiring sul metodo.

Esempio

Mettiamo in funzione l'IDE Eclipse e seguiamo i seguenti passaggi per creare un'applicazione Spring:

Passo Descrizione
1 Crea un progetto con un nome SpringExample e crea un pacchetto com.tutorialspoint sottosrc cartella nel progetto creato.
2 Aggiungere le librerie Spring richieste utilizzando l' opzione Aggiungi JAR esterni come spiegato nel capitolo Esempio Spring Hello World .
3 Crea classi Java TextEditor , SpellChecker e MainApp nel pacchetto com.tutorialspoint .
4 Crea il file di configurazione Beans Beans.xml sottosrc cartella.
5 Il passaggio finale consiste nel creare il contenuto di tutti i file Java e nel file di configurazione Bean ed eseguire l'applicazione come spiegato di seguito.

Ecco il contenuto di TextEditor.java file -

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker( ) {
      return spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

Di seguito è riportato il contenuto di un altro file di classe dipendente SpellChecker.java:

package com.tutorialspoint;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

Di seguito è riportato il contenuto del file MainApp.java file -

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}

Di seguito è riportato il file di configurazione Beans.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">

   <context:annotation-config/>

   <!-- Definition for textEditor bean without constructor-arg  -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker">
   </bean>

</beans>

Una volta terminata la creazione dei file di configurazione dei bean e dei sorgenti, eseguiamo l'applicazione. Se tutto va bene con la tua applicazione, verrà stampato il seguente messaggio:

Inside SpellChecker constructor.
Inside checkSpelling.

@Autowired su Proprietà

Puoi usare @Autowiredannotazione sulle proprietà per sbarazzarsi dei metodi setter. Quando passerai i valori delle proprietà autowired utilizzando <property>, Spring assegnerà automaticamente a quelle proprietà i valori o i riferimenti passati. Quindi, con l'utilizzo di @Autowired sulle proprietà, il tuoTextEditor.java il file diventerà il seguente:

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   @Autowired
   private SpellChecker spellChecker;

   public TextEditor() {
      System.out.println("Inside TextEditor constructor." );
   }
   public SpellChecker getSpellChecker( ){
      return spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

Di seguito è riportato il file di configurazione Beans.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">

   <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>

Una volta terminate le due modifiche precedenti nei file di configurazione dei bean e dei sorgenti, eseguiamo l'applicazione. Se tutto va bene con la tua applicazione, verrà stampato il seguente messaggio:

Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.

@Autowired on Constructors

Puoi applicare @Autowired anche ai costruttori. Un'annotazione @Autowired del costruttore indica che il costruttore deve essere cablato automaticamente durante la creazione del bean, anche se non vengono utilizzati elementi <constructor-arg> durante la configurazione del bean nel file XML. Controlliamo il seguente esempio.

Ecco il contenuto di TextEditor.java file -

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

Di seguito è riportato il file di configurazione Beans.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">

   <context:annotation-config/>

   <!-- Definition for textEditor bean without constructor-arg  -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker">
   </bean>

</beans>

Una volta terminate le due modifiche precedenti nei file di configurazione dei bean e dei sorgenti, eseguiamo l'applicazione. Se tutto va bene con la tua applicazione, verrà stampato il seguente messaggio:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Autowired con opzione (obbligatorio = false)

Per impostazione predefinita, l'annotazione @Autowired implica che la dipendenza è richiesta in modo simile all'annotazione @Required, tuttavia, puoi disattivare il comportamento predefinito usando (required=false) opzione con @Autowired.

L'esempio seguente funzionerà anche se non si passa alcun valore per la proprietà age ma richiederà comunque la proprietà name. Puoi provare questo esempio tu stesso perché è simile all'esempio di annotazione @Required tranne che soloStudent.java il file è stato modificato.

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class Student {
   private Integer age;
   private String name;

   @Autowired(required=false)
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   
   @Autowired
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
}