Exemple de référence du bean Spring EL
Dans Spring EL, vous pouvez référencer un bean et des propriétés imbriquées à l’aide d’un symbole «dot (.)». Par exemple, «bean.property_name».
public class Customer { @Value("#{addressBean.country}") private String country;
Dans l'extrait de code ci-dessus, il injecte la valeur de la propriété «country» du bean «addressBean» dans la classe «customer» actuelle, propriété «country».
EL de printemps dans l'annotation
Voir l'exemple suivant, vous montrer comment utiliser SpEL pour référencer un bean, une propriété de bean et également sa méthode.
package com.example.core; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{addressBean}") private Address address; @Value("#{addressBean.country}") private String country; @Value("#{addressBean.getFullAddress('example')}") private String fullAddress; //getter and setter methods @Override public String toString() { return "Customer [address=" + address + "\n, country=" + country + "\n, fullAddress=" + fullAddress + "]"; } }
package com.example.core; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("addressBean") public class Address { @Value("Block ABC, LakeView") private String street; @Value("98700") private int postcode; @Value("US") private String country; public String getFullAddress(String prefix) { return prefix + " : " + street + " " + postcode + " " + country; } //getter and setter methods public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Address [street=" + street + ", postcode=" + postcode + ", country=" + country + "]"; } }
Exécuter
Customer obj = (Customer) context.getBean("customerBean"); System.out.println(obj);
Sortie
Customer [address=Address [street=Block ABC, LakeView, postcode=98700, country=US] , country=US , fullAddress=example : Block ABC, LakeView 98700 US]
Spring EL en XML
Voir la version équivalente dans le fichier XML de définition de bean.
Télécharger le code source
Téléchargez-le -Spring3-EL-Bean-Reference-Example.zip (6 Ko)