Announcement Announcement Module
Collapse
No announcement yet.
Need some help to understand Anotations - Spring annotations Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need some help to understand Anotations - Spring annotations

    I am trying to learn Spring and Hibernate and i am really struggling to understand Annotations and how they work. Most of the example i am seeing on the Internet are annotation based examples so i need to understand how the annotations work first before i can learn Spring or Hibernate

    I have an idea of what they are and what they are used for. I know that they replace the xml configuration. I.e. You can configure beans directly within Java code using annotations. What i dont understand is how to use them and when they can be used.

    Trying to understand how this can be done i think it would be helpful if i see the difference between the two. I have here a simple Spring program. If i was to convert this sample program to use annotations what would i need to do?

    The reason i want to do it this way is because the program i have provided below is one that i understand very well (an example from the Spring in Action book that i am currently reading). If it is converted to an annotations version i will get an idea as to how and where annotations can be used.

    Any suggestions?

    Thanks in advance

    ----
    instrumentalist.xml

    Code:
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
        	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-2.0.xsd">
        	
        	<bean id="saxophone" class="com.sia.ch1.instrumentalist.Saxophone" />
        	<bean id="piano" class="com.sia.ch1.instrumentalist.Piano" />
        	
        	<!--  Injecting into bean properties Ken 1 -->
        	<bean id="kenny" class="com.sia.ch1.instrumentalist.Instrumentalist">
        		<property name="song" value="Jingle Bells"/>
        		<property name="instrument" ref="piano"/>		
        	</bean>	
        </beans>
    Instrumentalist interface

    Code:
        package com.sia.ch1.instrumentalist;
        public interface Instrument {
        	void play();
        }
    Instrumentalist implementor

    Code:
        package com.sia.ch1.instrumentalist;
        
        import com.sia.ch1.performer.PerformanceException;
        import com.sia.ch1.performer.Performer;
        
        public class Instrumentalist implements Performer{
        	
        	private Instrument instrument;
        	private String song;
        	
        	public Instrumentalist(){}
        	
        	public void perform() throws PerformanceException{
        		System.out.print("Playing " + song + " : ");		
        		instrument.play();
        	}
        	
        	public void setInstrument(Instrument instrument) {
        		this.instrument = instrument;
        	}	
        
        	public void setSong(String song) {
        		this.song = song;
        	}	
        }
    Instruments - Piano

    Code:
        package com.sia.ch1.instrumentalist;
        
        public class Piano implements Instrument{
        	public Piano(){}
        	public void play(){
        		System.out.println("PLINK PLINK");
        	}
        }
    Instruments - Saxophone

    Code:
        package com.sia.ch1.instrumentalist;
        
        public class Saxophone implements Instrument{
        	public Saxophone(){}
        	public void play(){
        		System.out.println("TOOT TOOT TOOT");
        	}
        }
    Main class

    Code:
        package com.sia.ch1.instrumentalist;
        
            import org.springframework.context.ApplicationContext;
            import org.springframework.context.support.FileSystemXmlApplicationContext;
            
            import com.sia.ch1.performer.PerformanceException;
            import com.sia.ch1.performer.Performer;
            
            public class InstrumentalistApp {
            	
            	public static void main(String[] args){
            		ApplicationContext ctx = new FileSystemXmlApplicationContext("c:\\projects\\test\\conf\\instrumentalist.xml");
            			
            		Performer performer = (Performer) ctx.getBean("kenny");
            		
            		try {
            			performer.perform();			
            		} catch (PerformanceException e) {
            			e.printStackTrace();
            		}
            	}	
            }
    Exception

    Code:
        package com.sia.ch1.performer;
        
        public class PerformanceException extends Exception {
        
        	public PerformanceException() {
        		super();
        		// TODO Auto-generated constructor stub
        	}
        
        	public PerformanceException(String message, Throwable cause) {
        		super(message, cause);
        		// TODO Auto-generated constructor stub
        	}
        
        	public PerformanceException(String message) {
        		super(message);
        		// TODO Auto-generated constructor stub
        	}
        
        	public PerformanceException(Throwable cause) {
        		super(cause);
        		// TODO Auto-generated constructor stub
        	}
        }

  • #2
    It depends... It depends on what you mean with annotations... There are basically 2 options, do you mean the java based configuration instead of xml or do you mean the annotations to specify the wiring information. Also do you meant the annotations which completely remove xml or do you still want to use xml or only remove the bean references...

    What seems like a simple question can be solved in different ways (and different combinations to be precise). Assuming no more xml and thus java based config.

    A one-on-one translation of your xml to a java config is

    Code:
    @Configuration
    public class InstrumentalistContextConfiguration {
    
      @Bean
      public Instrument piano() {
        return new Piano();
      }
    
      @Bean
      public Instrument saxophone() {
        return new Saxophone();
      }
    
      @Bean
      public Performer kenny() {
        Instrumentalist kenny = new Instrumentalist();
        kenny.setSong("Jingle Bells!");
        kenny.setInstrument(piano())
        return kenny;
      }
    
    }
    Loading
    Code:
    public class InstrumentalistApp {
            	
    	public static void main(String[] args){
    		ApplicationContext ctx = new AnnotationConfigApplicationContext(InstrumentalistContextConfiguration.class);
            			
       		Performer performer = (Performer) ctx.getBean("kenny");
            		
       		try {
       			performer.perform();			
       		} catch (PerformanceException e) {
       			e.printStackTrace();
       		}
       	}	
    }
    Instead of putting the beans in here explicitly you could also use @Component on the beans and use component scanning. You simply put @Component on the Piano and Saxophone class and put the ComponentScan on the configuration class. Remove the piano and saxophone methods. Create an attribute of type Instrument, put @Autowired on it and a @Qualifier (because you want the piano) and inject that dependent in the Instrumentalist bean (instead of the piano method). That is the description the implementation I leave to you...

    Comment

    Working...
    X