WELCOME Abdennour : Software engineer

Mar 29, 2012

Summary of Mkyong's Spring Core tutorials


Core Spring

Utility for Dependency to Interface:

1-conceals(cacher) complexity of implementation;
2-allows for swapping out implementation
==================
@Transactional
public A method(String s){
}

1.Spring JavaConfig (Spring 3.0)

1.1.Spring 3 JavaConfig example

Demonstrate the use of @Configuration and @Bean to define bean in Spring
-JavaConfig: allow developer to move bean definition and Spring configuration out of XML file into Java class.
Equivalence between Xml Cfg and JavaCfg
<bean id="helloBean" class="com.mkyong.hello.impl.HelloWorldImpl">

@Configuration
 public class AppConfig {
      @Bean(name="helloBean")
   public HelloWorld helloWorld() {
      return new HelloWorldImpl();    
   }
  }

Dependency Library:
see the Xml file (spring11.xml) =>spring-core,spring-context,cglib
Spring 3 JavaConfig @Import example

1.2.Spring 3 JavaConfig @import example

Demonstrate the use of @Import to organize beans in modular.
Equivalence between xmlCfg & JavaCfg in import
<import resource="config/customer.xml"/>         <import resource="config/scheduler.xml"/>

@Configuration
 @Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

2.Spring Dependency Injection (DI)

How Spring to do dependency Injection (DI) to manage object dependencies.

a)Via Setter :

 


2.1.Spring Dependency Injection (DI)

How Spring apply the Dependency Injection (DI) design 

pattern via Setter Injection and Constructor Injection.

2.2.Spring DI via setter method

Dependency injection a bean via setter method.

2.3.Spring DI via constructor

Dependency injection a bean via constructor.

2.4.Constructor injection type ambiguities in Spring

The constructor injection argument type ambiguities issue is 

always happened in a bean which contains multiple 

constructor methods with many arguments.
<constructor-arg>    
    <value>188</value>  
 </constructor-arg>

. In Spring, the argument type ’188′ is capable convert to int


Problem : In the case of ambiguite :

Spring show this message:...specify index and/or  type 

arguments for simple parameters to avoid type ambiguities

SOLUTION
   
        Specify the Type of every field in Constructor:

  Example:

  <constructor-arg type="java.lang.String">      
          
             <value>Abdennour</value>

   </constructor-arg>

3.Bean Basic

All the classes you need to use in Spring Ioc container are 

consider “bean”, and declared in Spring bean configuration 

file or via annotation.

3.1.Spring bean reference example

How beans access to each other by specify the bean 

references in same or different bean configuration file.


A)If the Bean and Reference In the Same File:

-referring to a bean in same XML file,

     ==>reference it with ‘ref‘ tag, ‘local‘ attribute.

<ref local="someBean"/>
<property name="outputGenerator" >                                                                                     
         <ref local="CsvOutputGenerator"/>   
</property>



B)If the Bean and The Reference in two differents files:
<ref bean="CsvOutputGenerator"/>

3.2.Inject value into bean properties in Spring

Three ways to inject value into bean properties:


A)WAY1(normal):
<bean id="FileNameGenerator" class="com..FileNameGenerator">                    
     <property name="name">                                        
           <value>abdennur</value>                          
       </property>
</bean>
B)WAY2(Shortcut):
<bean id="FileNameGenerator" class="com.FileNameGenerator">                         
   
               <property name="name" value="abdennur" />
</bean>
C)WAY3(“p” schema):
<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator"               p:name="mkyong" p:type="txt" />

3.3.Load multiple Spring bean configuration file


-When we have Spring beans' configuration files in differents 

folders(for Example, common folder, connection folder ..etc):


 i.create a Spring-All-Module.xml file,

 ii.put this file under project classpath.

 iii.  import the entire Spring bean files like this :

<import resource="common/Spring-Common.xml"/>
    <import resource="connection/Spring-Connection.xml"/>

3.4.Spring inner bean examples

Whenever a bean is used for one particular property only

it’s always advise to declare it as an inner bean(Bean interne)
<bean id="CustomerBean" class="com.Customer">
         <constructor-arg>                                               
                    <bean class="com.Person">
                                <property name="name" value="Abdennour" />
                                 <property name="age" value="28" />
                     </bean>                       
         </constructor-arg>
 </bean>

3.5.Spring bean scopes examples

Bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.

6 types of bean scopes supported :

1)singleton – Return a single bean instance per Spring IoC 

container(default scope ).

2)prototype – Return a new bean instance each time when 

requested

3)request – Return a single bean instance per HTTP request. *

4)session – Return a single bean instance per HTTP session. *

5)globalSession – Return a single bean instance per global 

HTTP session. *

6) thread : go to my tutorial because M. Mkyong don't write a

 tutorial for this type, as thread scope is new in spring 3. 

_______________________________



A)XML Definition of scope attribute:

<bean id="customerService" class="com.CustomerService"  scope="prototype"/>


B)Annotation Definition of scope attribute:
package slm.abdennour.customer;

@Service
@Scope("prototype")
public class CustomerService
{...}
<context:component-scan base-package="slm.abdennour.customer" />


3.6.Spring Collections (List, Set, Map, and Properties) example

Example to inject values into collections type (List, Set, Map,         


and Properties) : 


-List – <list/>

-Set – <set/>

-Map – <map/>

-Properties – <props/>



3.7.ListFactoryBean example

Create a concrete List collection class (ArrayList and 

LinkedList), and inject it into bean property.


-private List list;
------------------------
A)Method One:
<property name="lists">                                           
         <bean class="org.springframework.beans.factory.config.ListFactoryBean">
                 <property name="targetListClass">                     <value>java.util.ArrayList</value>                                                        </property>                                                    
                <property name="sourceList">
                        <list>                                                                                         
                              <value>1</value>                                                                                                        
                              <value>2</value>                                                                         
                               <value>3</value>                                                                        
                        </list>
                </property>                                    
 </bean>
                               </property>
B)Method 2(util:list) instead of org.springf....:
IL FAUT INCLURE THIS REF:
xmlns:util="http://www.springframework.org/schema/util"                
xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util-2.5.xsd">

<property name="lists">
         <util:list list-class="java.util.ArrayList">                                                     
                        <value>1</value>
                         <value>2</value>                                                              
                         <value>3</value>                                               
         </util:list>                
</property>

3.8.SetFactoryBean example

Create a concrete Set collection class (HashSet and TreeSet), and inject it into bean property


3.9.MapFactoryBean example

Create a concrete Map collection class (HashMap and TreeMap), and inject it into bean property.



3.10.Spring inject Date into bean property – CustomDateEditor

Normally, Spring is accept date variable, here’s a tip to use CustomDateEditor to workaround it.
A)Method1(FactoryBean):
-The factory method will call SimpleDateFormat.parse() to convert String into Date object automatically.
 <bean id="dateFormat" class="java.text.SimpleDateFormat">
        <constructor-arg value="yyyy-MM-dd" />
    </bean>
<property name="date">                                         
             <bean factory-bean="dateFormat" factory-method="parse">                                                 <constructor-arg value="2010-01-31" />                                                


</bean>                            
</property>
B)Method2: See the Code by and the Shop (toInjectDateByString.xml)
1)Declares a CustomDateEditor class to convert String into java.util.Date.
2)declares another “CustomEditorConfigurer”, to make Spring convert bean properties whose type is java.util.Date.

3.11.Spring PropertyPlaceholderConfigurer example

Externalize the deployment details into a properties file, and access from bean configuration file via a special format – ${variable}.
EXAMPLE:
*******************************
IN [DB.properties]************
*******************************
jdbc.driverClassName=com.mysql.jdbc.Driver                
jdbc.url=jdbc:mysql://localhost:3306/abdennourDB 
jdbc.username=root
jdbc.password=password
*******************************
IN [.[SpringFile].xml]************
*******************************
<bean                  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
                               <property name="location">                                   <value>DB.properties</value>                               </property>                
</bean>
…...
<property name="url" value="${jdbc.url}" />

3.12.Spring bean configuration inheritance

-Inheritance is very useful for a bean to share common values, properties or configuration.
<bean id="BaseCustomerMalaysia" class="com.mkyong.common.Customer">
                                   <property name="country" value="Malaysia" />       
</bean> 
               <bean id="CustomerBean" parent="BaseCustomerMalaysia">  
                        <property name="action" value="buy" />
                           <property name="type" value="1" />
               </bean>
==>The ‘CustomerBean’ bean just inherited the country property from its parent (‘BaseCustomerMalaysia’)
Inheritance with abstract:
 <bean id="BaseCustomer" class="com.Customer" abstract="true">
=>We can't instantiate an abstract Bean.
=> a bean can inherit from abstract bean
=> it's not nesscery to specify the class of Abstract => We Call it pure template.
=>When we don't specify the Class of Abstract Bean,Every Bean has some fields have the same name&type as Abstract Bean , that Bean can inherit from the abstract.
 Override it:
=>We can override(Ecrase) the field of parent in bean of Child.

3.13.Spring dependency checking

Spring comes with 4 dependency checking modes to make sure the required properties have been set in bean.
1)none –(By Default) No dependency checking.
2)simple – If any properties of primitive type (int, long,double…) and collection types (map, list..) have not been set, UnsatisfiedDependencyException will be thrown.
3)objects – If any properties of object type have not been set, UnsatisfiedDependencyException will be thrown.
4)all – If any properties of any type have not been set, an UnsatisfiedDependencyException will be thrown.
public class Customer  {               
          private Person person;
          private int type;    
          private String action; 
                //getter and setter methods
}
public class Person  {
                private String name;
                private String address;
                private int age;
}
<bean id="CustomerBean" class="com.Customer"   dependency-check="simple">
<bean id="CustomerBean" class="com.Customer"   dependency-check="objects">
<bean id="CustomerBean" class="com.Customer"   dependency-check="all">

3.14.Spring dependency checking with @Required Annotation

Dependency checking in annotation mode.
1)apply @Required in setPerson() method to make sure the person property has been set.
public class Customer  {
...
                @Required       
  public void setPerson(Person person)
          {                    this.person = person;    }
2)register an RequiredAnnotationBeanPostProcessor to aware(conscient) of the @Required annotation in bean cfg file.there are 2 Ways:
2)a.By <context:annotation-config />:
2)b. By Including RequiredAnnotationBeanPostProcessor
<bean  class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

3.15.Custom @Required-style annotation

Create a custom @Required-style annotation ,which is equivalent to @Required annotation.
@Required=>used to make sure a particular property has been set.
@Required-style=>f you are migrate your existing project to Spring framework or have your own @Required-style annotation for whatever reasons.
EXAMPLE
(Before Migrating):
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Mandatory {
package your.company.package;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
}
public class Customer
  {            private Person person;
                private int type;               private String action;    
@Mandatory   
public void setPerson(Person person)
{                              this.person = person;    }             
//getter and setter methods }

TO MIGRATE:
=>include @mandatory in xml file:
<bean  class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
                <property name="requiredAnnotationType" value="com.mkyong.common.Mandatory"/> </bean>
==>Now,@Required-style annotation named @Mandatory, EQUIVALENT to @Required annotation.

3.16.Bean InitializingBean and DisposableBean example

Perform certain actions upon bean initialization and destruction. (interface)
1)public class CustomerService implements InitializingBean, DisposableBean {       
        String message;
                public String getMessage() {        return message;            }             
          public void setMessage(String message) {                  this.message = message;          }  
                public void afterPropertiesSet() throws Exception {       
 System.out.println("Init method after properties are set : " + message);           }  
               public void destroy() throws Exception {             
  System.out.println("Spring Container is destroy! Customer clean up");
}
2) ON test instantiate context by :
ConfigurableApplicationContext context =
            new ClassPathXmlApplicationContext....
3)in the end of test, onvoke context.close() to declenche destroy() method of customer.
=>The afterPropertiesSet() method is called, after the message property is set;
=>the destroy() method is call after the context.close();

3.17.Bean init-method and destroy-method example(Perfect compared to the previous)

Perform certain actions upon bean initialization and destruction. (XML)
=INstead of implementing InitializingBean, DisposableBean  :
=>we define th init method & the destroy method in xml bean. And we are free to choose the name of this methods.
=>Implement this methods in the Bean java.
<bean id="customerService" class="com.CustomerService"  init-method="initIt" destroy-method="cleanUp">
=>The initIt() method is called, after the message property is set,
=>and the cleanUp() method is called after the context.close();

3.18.Bean @PostConstruct and @PreDestroy example(With Annotation)

Perform certain actions upon bean initialization and destruction. (Annotation)
1)import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy; 
 public class CustomerService {
                String message;  //Getter &Setter
                @PostConstruct              public void initIt() throws Exception {
                  System.out.println("Init method after properties are set : " + message);          }  
      @PreDestroy              public void cleanUp() throws Exception {
                  System.out.println("Spring Container is destroy! Customer clean up");             }
   }
2)To aware @Post... @Pre....Add :
A==<context:annotation-config />‘  in xml Cfg Spring
or
B==register ‘CommonAnnotationBeanPostProcessor‘
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
=>initIt() method (@PostConstruct) is called, after the message property is set
=>the cleanUp() method (@PreDestroy) is call after the context.close();
=====================================================

4.Spring Expression Language (Spring 3.0)

Spring 3.0 introduces features rich and powerful expression language known as Spring expression language, or Spring EL.

4.1.Spring EL hello world example

Quick start to use Spring expression language (EL).
·         EL Spring :evaluated or executed during the bean creation time  via XML or Annotations.
·         USe El Spring to inject String, integer and bean into property, both in XML and annotation.
·         The SpEL are enclosed with #{ SpEL expression },
=>Exple:<property name="item" value="#{itemBean}" />
EQUIVALENCE BETWEEN XML & ANNOTATIONS:
<bean id="itemBean" class="com.Item">
                               <property name="name" value="itemA" />
                               <property name="qty" value="10" />  
</bean>  
                <bean id="customerBean" class="com.Customer">                     
<property name="item" value="#{itemBean}" />
                               <property name="itemName" value="#{itemBean.name}" />
                </bean>

@Component("customerBean")
public class Customer {
                @Value("#{itemBean}")
    private Item item; 
     @Value("#{itemBean.name}")
     private String itemName;
------------------------------------------------
@Component("itemBean")
 public class Item {
                @Value("itemA") //inject String directly            
private String name;     
    @Value("10") //inject interger directly           
   private int qty;
-------------------------------IN  XML-----------------------------------
<context:component-scan base-package="com" />

=@Value to define Spring EL.

4.2.Spring EL bean reference example

Reference bean, bean property using a dot (.) symbol.
EXAMPLE:
1*With Annotations:
@Value("#{addressBean.getFullAddress('mkyong')}")                
private String fullAddress;
@Component("addressBean")
public class Address {  
     @Value("Block ABC, LakeView")
       private String street;
    ….....
                public String getFullAddress(String prefix) {
                               return prefix + " : " + street + " " + postcode + " " + country;                 }


2*With XMl:
<bean    .........
        <property name="fullAddress" value="#{addressBean.getFullAddress('mkyong')}" />
                </bean>             
<bean id="addressBean" class="com.Address">

4.3.Spring EL method invocation example

Call bean method in direclty.
EXAMPLE:
2*EXAMPLE WITH XML:

@Component("customerBean")
public class Customer {
                @Value("#{'abdennour'.toUpperCase()}")                
       private String name;
@Value("#{priceBean.getSpecialPrice()}")
       private double amount;
…..
@Component("priceBean")
public class Price {
                public double getSpecialPrice() {
         return new Double(99.99);               }

<bean id="customerBean" class="com.Customer">
       <property name="name" value="#{'abdennour'.toUpperCase()}" />
                <property name="amount" value="#{priceBean.getSpecialPrice()}" />       
</bean>
                <bean id="priceBean" class="com.Price" />

4.4.Spring EL operators example

Spring EL suppots most of the standard relational, logical and mathematical operators.

1.Relational operators – equal (==, eq), not equal (!=, ne), less than (<, lt),
less than or equal (<= , le), greater than (>, gt), and greater than or equal (>=, ge).
1.a.in Annotations:
@Value("#{1 == 1}") //true       
private boolean testEqual;        
@Value("#{1 <1}") //false         
private boolean testNotEqual;
1.b.in XML:
<property name="testNotEqual" value="#{1 == 1}" />                  
<property name="testLessThan" value="#{1 lt 1}" />
2.Logical operators – and, or, and not (!).
2.a.in Annotations:
@Value("#{numberBean.no == 999 and numberBean.no < 900}") //false         
private boolean testAnd;
2.b.in XML:
<property name="testAnd" value="#{numberBean.no == 999 and numberBean.no lt 900}" />

3.Mathematical operators – addition (+), Subtraction (-), Multiplication (*), division (/), modulus (%) and exponential power (^).
3.a.in Annotations:
@Value("#{'1' + '@' + '1'}") //1@1          
private String testAddString;
                @Value("#{2 ^ 2}") //4.0            
private double testExponentialPower;
3.b.in XML:
<property name="testAddString" value="#{'1' + '@' + '1'}" />
<property name="testExponentialPower" value="#{2 ^ 2}" />
==>In XML, symbol like “less than” is always not support, instead,
you should use the textual equivalents shown above, for example, (‘<‘ = ‘lt‘) and (‘<=‘ = ‘le‘).

4.5.Spring EL ternary operator (if-then-else) example

Conditional check , if else then.
Tenery Operator =>condition ? true : false
EXAMPLE:
@Component("customerBean")
public class Customer { 
      @Value("#{itemBean.qtyOnHand < 100 ? true : false}")   
       private boolean warning;
…...}
@Component("itemBean")
public class Item { 
    @Value("99")
       private int qtyOnHand;

<bean id="customerBean" class="com.mkyong.core.Customer">                        
      <property name="warning"                            value="#{itemBean.qtyOnHand &lt; 100 ? true : false}" />
                </bean>             
<bean id="itemBean" class="com.Item">
         <property name="qtyOnHand" value="99" />       
</bean>


4.6.Spring EL Arrays, Lists, Maps example

Works with Map and List.
*use Spring EL to get value from Map and List.
EXAMPLE:
@Component("customerBean")
public class Customer {
                @Value("#{testBean.map['MapA']}")
     private String mapA;
                @Value("#{testBean.list[0]}")
      private String list;

@Component("testBean")
public class Test {
                private Map<String, String> map;
  private List<String> list;
                public Test() {
     map = new HashMap<String, String>();
     map.put("MapA", "This is A");  //.....
                list = new ArrayList<String>();
      list.add("List0");  //....



*IN XML :
<bean id="customerBean" class="com.Customer">     
        <property name="mapA" value="#{testBean.map['MapA']}" />                  
        <property name="list" value="#{testBean.list[0]}" />
                </bean>             
<bean id="testBean" class="com.Test" />

4.7.Spring EL regular expression example

Regular expression to evaluate condition.
=>the keywords which used in this context is : “matches“
EXAMPLES:
a.test whether ‘n‘ is a valid digit via regular expression ‘\\d+‘.
        @Value("#{'100' matches '\\d+' }")              
        private boolean isDigit;
b.several Examples:
@Component("customerBean")
 public class Customer {
                // email regular expression
                String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)" +                                      "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";             
// if this is a digit?
                @Value("#{'100' matches '\\d+' }")
                private boolean validDigit;  // if this is a digit + ternary operator              
@Value("#{ ('100' matches '\\d+') == true ? " +                                            "'yes this is digit' : 'No this is not a digit'  }")   
private String msg;         // if this emailBean.emailAddress contains a valid email address?          
@Value("#{emailBean.emailAddress matches customerBean.emailRegEx}")
                private boolean validEmail;        //getter and setter methods, and constructor  }
==========
@Component("emailBean")
public class Email {
                @Value("nospam@abc.com")
    String emailAddress;

4.8.Test Spring EL with ExpressionParser

Show you how to test Spring El easily.
it supports many functionalities,
ExpressionParser parser = new SpelExpressionParser();
EXAMPLE1:(evaluate the literal string expression)
Expression exp = parser.parseExpression("'put spel expression here'");
String msg = exp.getValue(String.class);
EXAMPLE2:
Item item = new Item("abdennour", 100);
StandardEvaluationContext itemContext = new StandardEvaluationContext(item);
  //display the value of item.name property
Expression exp = parser.parseExpression("name");
String msg = exp.getValue(itemContext, String.class);
EXAMPLE3://method invocation
                               Expression exp2 = parser.parseExpression("'Hello World'.length()");
                               int msg2 = (Integer) exp2.getValue();                  
EXAMPLE4://create an item object                       
Item item = new Item("abdennour", 100);
                               //test EL with item object                          
StandardEvaluationContext itemContext = new StandardEvaluationContext(item);
                               //display the value of item.name property
                               Expression exp4 = parser.parseExpression("name");                   
String msg4 = exp4.getValue(itemContext, String.class);
                               System.out.println(msg4); 
                               //test if item.name == 'abdennour'      
                Expression exp5 = parser.parseExpression("name == 'abdennour'");
                               boolean msg5 = exp5.getValue(itemContext, Boolean.class);

5.Spring Auto Component Scanning


Spring is able to scan, detect and register your bean automatically.

5.1.Spring Auto scanning components

Enable Spring to auto scan, detect and register your beans.

5.2.Spring Filter components in auto scanning

Example to filter certain components in auto scanning mode.

6.Spring AutoWiring Bean


Spring ‘auto-wiring’ modes to wire or beans automatically, both in XML and annotation.

6.1.Spring Auto-Wiring Beans

Summary of 5 types auto wiring modes in Spring.
1)no – Default, no auto wiring, set it manually via “ref” attribute
=>, you need to wire your bean via ‘ref’ attribute.
  <bean      …..<property name="person" ref="person" />          </bean>  
                <bean id="person" class="com.Person" />

2)byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
=>, since the name of “person” bean is same with the name of the “customer” bean’s property (“person”),
 so, Spring will auto wired it via setter method – “setPerson(Person person)“.
        <bean id="customer" class="com.Customer" autowire="byName" />
<bean id="person" class="com.Person" />

3)byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.
==>since the data type of “person” bean is same as the data type of the “customer” bean’s property (Person object)
, so, Spring will auto wired it via setter method .
<bean id="customer" class="com.Customer" autowire="byType" /> 
                <bean id="person" class="com.mkyong.common.Person" />
4)constructor – byType mode in constructor argument.
==>since the data type of “person” bean is same as the constructor argument data type in “customer” bean’s property (Person object)
, so, Spring auto wired it via constructor method – “public Customer(Person person)“.
<bean id="customer" class="com.Customer" autowire="constructor" /
                <bean id="person" class="com.Person" />


5)autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.
<bean id="customer" class="com.Customer" autowire="autodetect" />           
<bean id="person" class="com.Person" />
NOTES:
=====>Combine 'auto-wire' &  'dependency-check' together ,to make sure the property is always auto-wire successfully.
<bean id="customer" class="comCustomer"     autowire="autodetect" dependency-check=objects />

6.2.Spring Autowiring by Type

If data type of a bean is compatible with the data type of other bean property, auto wire it.

6.3.Spring Autowiring by Name

If the name of a bean is same as the name of other bean property, auto wire it.

6.4.Spring Autowiring by Constructor

Actually, it’s autowiring by Type in constructor argument.

6.5.Spring Autowiring by AutoDetect

It means chooses “autowire by constructor” if default constructor is found, otherwise uses “autowire by type”.

6.6.Spring Autowiring with @Autowired annotation

Examples to show how to define ‘auto-wiring’ modes in annotation.
*Register AutowiredAnnotationBeanPostProcessor(To enable @Autowired)
1. Include <context:annotation-config />  in XML Beans Configuration.
or
2.Include AutowiredAnnotationBeanPostProcessor:
=><bean  class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
*Examples:
1. @Autowired setter method
@Autowired
public void setPerson(Person person) {
             this.person = person;      }

2. @Autowired construtor
@Autowired    
public Customer(Person person) {
                   this.person = person;                }

3. @Autowired field
@Autowired
private Person person;

6.7.Spring Autowiring @Qualifier example

it's mean :which bean is qualify to autowired on a field.
PB:When two beans were defined by the same type and we  have @Autowired field.
=>it hits below exception.
public class Customer { 
                @Autowired    
private Person person;
<bean id="personB" class="com.Person" >
<bean id="personA" class="com.Person" >
SOLUTION: Add @Qualifier to avoid confusion .
public class Customer { 
     @Autowired 
     @Qualifier("personA")
       private Person person;

==========================
=>the following Summary is about "Spring AOP"(إن شاء الله)


1 comment:

  1. If you think that Maven could help your project, you can find out more information about in the "About Maven" section of the navigation. This includes an in-depth description of what Maven is, a list of some of its main features, and a set of frequently asked questions about what Maven is.

    spring custom validator example

    ReplyDelete