Spring Autowire ByType ByName AutoDetect Project

Click here to download eclipse supported ZIP file



This is AutowireTestByAutoDetect.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

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

/**
 @author Chandra Vardhan
 
 */
public class AutowireTestByAutoDetect {

  /**
   @param args
   */
  public static void main(String[] args) {
    String configLocation = "autoDetect.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        configLocation);
    String name = "duke";
    Performer performer = (PerformerapplicationContext.getBean(name);
    performer.perform();
  }

}


This is AutowireTestByConstructor.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

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

/**
 @author Chandra Vardhan
 
 */
public class AutowireTestByConstructor {

  /**
   @param args
   */
  public static void main(String[] args) {

    String configLocation = "byConstructor.xml";

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        configLocation);

    String name = "duke";

    Performer performer = (PerformerapplicationContext.getBean(name);

    performer.perform();

  }

}


This is AutowireTestByName.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 @author Chandra Vardhan
 
 */
public class AutowireTestByName {
  
  private final static Logger LOGGER = Logger.getLogger(AutowireTestByName.class);


  /**
   @param args
   */
  public static void main(String[] args) {

    String configLocation = "byName.xml";

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        configLocation);

    String name = "kenny";

    Performer performer = (PerformerapplicationContext.getBean(name);

    performer.perform();

    LOGGER.info("============================================");
    
    String name2 = "kenny2";

    Performer performer2 = (PerformerapplicationContext.getBean(name2);

    performer2.perform();

  }

}


This is AutowireTestByType.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 @author Chandra Vardhan
 
 */
public class AutowireTestByType {

  private final static Logger LOGGER = Logger.getLogger(AutowireTestByType.class);

  
  /**
   @param args
   */
  public static void main(String[] args) {

    String configLocation = "byType.xml";

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        configLocation);

    String name = "kenny";

    Performer performer = (PerformerapplicationContext.getBean(name);

    performer.perform();

    LOGGER.info("============================================");
    
    String name2 = "kenny2";

    Performer performer2 = (PerformerapplicationContext.getBean(name2);

    performer2.perform();

  }

}


This is Gitter.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;


/**
 @author Chandra Vardhan
 
 */

public class Gitter implements Instrument {

  private final static Logger LOGGER = Logger.getLogger(Gitter.class);

  
  public Gitter() {
    
  }
  
  public void play() {
    
    LOGGER.info("TO TO TI TI  TE TE...TOOOOOO");

  }

}


This is Harmonia.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;



/**
 @author Chandra Vardhan
 
 */

public class Harmonia implements Instrument {
  
  private final static Logger LOGGER = Logger.getLogger(Harmonia.class);

  
  public Harmonia() {
    
  }
  
  public void play() {
    
    LOGGER.info("HAR HAR...moooo moooooo...Harmonia");

  }

}


This is Instrument.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

/**
 @author Chandra Vardhan
 
 */


public interface Instrument {

   void play();

}


This is InstrumentList.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 
 */

public class InstrumentList implements Performer {
  
  private final static Logger LOGGER = Logger.getLogger(InstrumentList.class);

  
  private String song;
  private Instrument instrument;

  public InstrumentList() {

  }

  public Instrument getInstrument() {
    return instrument;
  }

  public void setInstrument(Instrument instrument) {
    this.instrument = instrument;
  }

  public String getSong() {
    return song;
  }

  public void setSong(String song) {
    this.song = song;
  }

  public void perform() {

    LOGGER.info("Playing " + song);
    instrument.play();

  }

}


This is InstrumentList2.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 
 */

public class InstrumentList2 implements Performer {

  private final static Logger LOGGER = Logger.getLogger(InstrumentList2.class);
  
  private String song;
  private Instrument instrument;

  public InstrumentList2() {

  }

  public Instrument getInstrument() {
    return instrument;
  }

  public void setInstrument(Instrument instrument) {
    this.instrument = instrument;
  }

  public String getSong() {
    return song;
  }

  public void setSong(String song) {
    this.song = song;
  }

  public void perform() {
    LOGGER.info("Playing " + song);
    instrument.play();
  }

}


This is Jugg.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 
 */

public class Jugg implements Performer {

  private final static Logger LOGGER = Logger.getLogger(Jugg.class);

  
  private int beanBags = 3;

  public Jugg() {

  }

  public Jugg(int beanBags) {

    this.beanBags = beanBags;
  }

  public void perform() {
    
    LOGGER.info("JUGGLING " + beanBags + " BEANBAGS");

  }

}


This is Performer.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

/**
 @author Chandra Vardhan
 
 */

public interface Performer {

  void perform();
}


This is Piano.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 
 */

public class Piano implements Instrument {
  
  private final static Logger LOGGER = Logger.getLogger(Piano.class);

  public void play() {

    LOGGER.info("PINK PINK PUKK PUKKKKK POOOOOOOO...");

  }

}


This is Poem.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;


/**
 @author Chandra Vardhan
 
 */

public interface Poem {

  public void recite();

}


This is PoemImpl.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;



/**
 @author Chandra Vardhan
 
 */

public class PoemImpl implements Poem {
  
  private final static Logger LOGGER = Logger.getLogger(PoemImpl.class);


  private static String[] LINES = {
      "Am chandravardhan, done my gradution in KITS!!!",
      "Am very much open friendly because I am working with open source technologies!!!",
      "Am sincerely looking for a change!!!" };

  public PoemImpl() {

  }

  public void recite() {

    LOGGER.info("Am recited....");

    for (int i = 0; i < LINES.length; i++) {

      LOGGER.info(LINES[i]);
    }

  }

}


This is PoemImpl2.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;


/**
 @author Chandra Vardhan
 
 */

public class PoemImpl2 implements Poem {
  
  private final static Logger LOGGER = Logger.getLogger(PoemImpl2.class);


  private static String[] LINES = {
      "Am Chandra Vardhan, done my gradution in Kamala College!!!",
      "Am friendly minded because I am working with open source technologies!!!",
      "Am sincerely looking for a change!!!" };

  public PoemImpl2() {

  }

  public void recite() {

    LOGGER.info("Am recited....PoemImpl2");

    for (int i = 0; i < LINES.length; i++) {

      LOGGER.info(LINES[i]);
    }

  }

}


This is PoeticJugg.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

/**
 @author Chandra Vardhan
 
 */
public class PoeticJugg extends Jugg {
  
  private final static Logger LOGGER = Logger.getLogger(PoeticJugg.class);


  private Poem poem;

  public Poem getPoem() {
    return poem;
  }

  @Autowired
  public void setPoem(Poem poem) {
    this.poem = poem;
  }

  private PoeticJugg() {

  }

  private PoeticJugg(Poem poem) {

    super();
    this.poem = poem;
  }

  private PoeticJugg(Poem poem, int beanBags) {

    super(beanBags);

    this.poem = poem;

  }

  public void perform() {
  super.perform();
    LOGGER.info("while reciting....");
    poem.recite();

  }

}


This is TestBean.java file having the source code to execute business logic.


 

    
package com.cv.spring.annotation.autowire;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.util.ObjectUtils;

/**
 @author Chandra Vardhan
 
 */
public class TestBean implements BeanNameAware, BeanFactoryAware, Comparable<Object> {

  private String beanName;

  private String country;

  private BeanFactory beanFactory;

  private boolean postProcessed;

  private String name;

  private String sex;

  private int age;

  private boolean jedi;

  private String touchy;

  private String[] stringArray;

  private Integer[] someIntegerArray;

  private Date date = new Date();

  private Float myFloat = new Float(0.0);

  private Collection friends = new LinkedList();

  private Set someSet = new HashSet();

  private Map someMap = new HashMap();

  private List someList = new ArrayList();

  private Properties someProperties = new Properties();

  private boolean destroyed;

  private Number someNumber;


  private Boolean someBoolean;

  private List otherColours;

  private List pets;


  public TestBean() {
  }

  public TestBean(String name) {
    this.name = name;
  }

  
  public TestBean(List someList) {
    this.someList = someList;
  }

  public TestBean(Set someSet) {
    this.someSet = someSet;
  }

  public TestBean(Map someMap) {
    this.someMap = someMap;
  }

  public TestBean(Properties someProperties) {
    this.someProperties = someProperties;
  }


  public void setBeanName(String beanName) {
    this.beanName = beanName;
  }

  public String getBeanName() {
    return beanName;
  }

  public void setBeanFactory(BeanFactory beanFactory) {
    this.beanFactory = beanFactory;
  }

  public BeanFactory getBeanFactory() {
    return beanFactory;
  }

  public void setPostProcessed(boolean postProcessed) {
    this.postProcessed = postProcessed;
  }

  public boolean isPostProcessed() {
    return postProcessed;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public boolean isJedi() {
    return jedi;
  }

  public void setJedi(boolean jedi) {
    this.jedi = jedi;
  }

  
  public String getTouchy() {
    return touchy;
  }

  public void setTouchy(String touchythrows Exception {
    if (touchy.indexOf('.'!= -1) {
      throw new Exception("Can't contain a .");
    }
    if (touchy.indexOf(','!= -1) {
      throw new NumberFormatException("Number format exception: contains a ,");
    }
    this.touchy = touchy;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public String[] getStringArray() {
    return stringArray;
  }

  public void setStringArray(String[] stringArray) {
    this.stringArray = stringArray;
  }

  public Integer[] getSomeIntegerArray() {
    return someIntegerArray;
  }

  public void setSomeIntegerArray(Integer[] someIntegerArray) {
    this.someIntegerArray = someIntegerArray;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

  public Float getMyFloat() {
    return myFloat;
  }

  public void setMyFloat(Float myFloat) {
    this.myFloat = myFloat;
  }

  public Collection getFriends() {
    return friends;
  }

  public void setFriends(Collection friends) {
    this.friends = friends;
  }

  public Set getSomeSet() {
    return someSet;
  }

  public void setSomeSet(Set someSet) {
    this.someSet = someSet;
  }

  public Map getSomeMap() {
    return someMap;
  }

  public void setSomeMap(Map someMap) {
    this.someMap = someMap;
  }

  public List getSomeList() {
    return someList;
  }

  public void setSomeList(List someList) {
    this.someList = someList;
  }

  public Properties getSomeProperties() {
    return someProperties;
  }

  public void setSomeProperties(Properties someProperties) {
    this.someProperties = someProperties;
  }

  public Number getSomeNumber() {
    return someNumber;
  }

  public void setSomeNumber(Number someNumber) {
    this.someNumber = someNumber;
  }


  public Boolean getSomeBoolean() {
    return someBoolean;
  }

  public void setSomeBoolean(Boolean someBoolean) {
    this.someBoolean = someBoolean;
  }

  

  public List getOtherColours() {
    return otherColours;
  }

  public void setOtherColours(List otherColours) {
    this.otherColours = otherColours;
  }

  public List getPets() {
    return pets;
  }

  public void setPets(List pets) {
    this.pets = pets;
  }


  /**
   @see ITestBean#exceptional(Throwable)
   */
  public void exceptional(Throwable tthrows Throwable {
    if (t != null) {
      throw t;
    }
  }

  public void unreliableFileOperation() throws IOException {
    throw new IOException();
  }
  /**
   @see ITestBean#returnsThis()
   */
  public Object returnsThis() {
    return this;
  }

  /**
   @see IOther#absquatulate()
   */
  public void absquatulate() {
  }

  public int haveBirthday() {
    return age++;
  }


  public void destroy() {
    this.destroyed = true;
  }

  public boolean wasDestroyed() {
    return destroyed;
  }


  public boolean equals(Object other) {
    if (this == other) {
      return true;
    }
    if (other == null || !(other instanceof TestBean)) {
      return false;
    }
    TestBean tb2 = (TestBeanother;
    return (ObjectUtils.nullSafeEquals(this.name, tb2.name&& this.age == tb2.age);
  }

  public int hashCode() {
    return this.age;
  }

  public int compareTo(Object other) {
    if (this.name != null && other instanceof TestBean) {
      return this.name.compareTo(((TestBeanother).getName());
    }
    else {
      return 1;
    }
  }

  public String toString() {
    return this.name;
  }

}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">.0" encoding="UTF-8"?> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring.annotation</groupId> <artifactId>SpringAutowireByTypeNameAutoDetect</artifactId> <name>SpringAutowireByTypeNameAutoDetect</name> <packaging>jar</packaging> <version>1.0</version> <properties> <java-version>1.8</java-version> <log4j-version>1.2.16</log4j-version> <org.springframework-version>4.1.6.RELEASE</org.springframework-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>


This is autoDetect.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" default-autowire="byName">
<bean id="duke" class="com.cv.spring.annotation.autowire.PoeticJugg" scope="prototype"/>
<bean id="poem2" class="com.cv.spring.annotation.autowire.PoemImpl" scope="prototype" primary="true"/>
<bean id="poem" class="com.cv.spring.annotation.autowire.PoemImpl2" scope="prototype" />
<bean id="poem3" class="com.cv.spring.annotation.autowire.PoemImpl2" scope="prototype" />
</beans>


This is byConstructor.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<bean id="duke" class="com.cv.spring.annotation.autowire.PoeticJugg" scope="prototype" autowire="constructor" />
<bean id="poem2" class="com.cv.spring.annotation.autowire.PoemImpl" scope="prototype" />
<bean id="poem" class="com.cv.spring.annotation.autowire.PoemImpl2" scope="prototype" />
<bean id="kenny" class="com.cv.spring.annotation.autowire.InstrumentList" autowire="byName">
<property name="song" value="JingleBells" />
</bean>
<bean id="kenny2" class="com.cv.spring.annotation.autowire.InstrumentList2"
autowire="byName">
<property name="song" value="jinngle jinngle sab ke ..." />
</bean>
<bean name="instrument" class="com.cv.spring.annotation.autowire.Gitter" />
<bean name="gitter" class="com.cv.spring.annotation.autowire.Gitter" />
<bean name="harmonia" class="com.cv.spring.annotation.autowire.Harmonia" />
<bean name="piano" class="com.cv.spring.annotation.autowire.Piano"
autowire-candidate="false" />
</beans>


This is byName.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<bean id="kenny" class="com.cv.spring.annotation.autowire.InstrumentList" autowire="byName">
<property name="song" value="JingleBells" />
<property name="instrument" ref="instrument"></property>
</bean>
<bean id="kenny2" class="com.cv.spring.annotation.autowire.InstrumentList2" autowire="byType">
<property name="song" value="jinngle jinngle sab ke ..." />
<property name="instrument" ref="harmonia"></property>
</bean>
<bean name="instrument" class="com.cv.spring.annotation.autowire.Gitter" primary="true"/>
<bean name="harmonia" class="com.cv.spring.annotation.autowire.Harmonia" scope="prototype" />
<!-- <bean name="instrument" class="com.cv.spring.annotation.autowire.Harmonia" scope="prototype" /> --><!-- If u take this instrument here then it will be the problem...
Even though InstrumentList2(bean) also has same instrument property and it is also trying to use autowire byName then it is a problem... Because we cannot take two beans with same/id ...
And there is no problem when we are taking same bean implementation class wired with two different lists like(InstrumentList,InstrumentList2) or beans (kenny,kenny2)...-->
<bean name="gitter" class="com.cv.spring.annotation.autowire.Gitter" />
<bean name="piano" class="com.cv.spring.annotation.autowire.Piano" autowire-candidate="false"/>
</beans>


This is byType.xml file having the spring configuration properties.


 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="kenny" class="com.cv.spring.annotation.autowire.InstrumentList" autowire="byName">
<property name="song" value="JingleBells" />
</bean>
<bean id="kenny2" class="com.cv.spring.annotation.autowire.InstrumentList2"
autowire="byType">
<property name="song" value="jinngle jinngle sab ke ..." />
</bean>
<bean name="instrument" class="com.cv.spring.annotation.autowire.Gitter" />
<bean name="harmonia" class="com.cv.spring.annotation.autowire.Harmonia" primary="true" />
<bean name="piano" class="com.cv.spring.annotation.autowire.Piano" />
<!-- <bean name="piano" class="com.cv.spring.annotation.autowire.Piano" autowire-candidate="false"/> -->
</beans>



This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment