Spring Framework example 3

DataService.java

package spring.example3; public class DataService { private Consumer consumer;//object reference will be injected at runtime private Producer producer;//object reference will be injected at runtime public void execute(){ consumer.consume(producer.produce()); } public void setConsumer(Consumer consumer) { this.consumer = consumer; } public void setProducer(Producer producer) { this.producer = producer; } }

Executor.java

package spring.example3; //It uses dependency Injection import org.springframework.beans.factory.support.*; import org.springframework.core.io.ClassPathResource; public class Executor { public static void main(String ar[]){ DefaultListableBeanFactory bf=new DefaultListableBeanFactory(); BeanDefinitionReader reader=new PropertiesBeanDefinitionReader(bf); reader.loadBeanDefinitions(new ClassPathResource("spring/example3/producer-consumer.properties")); DataService ds=(DataService)bf.getBean("service"); ds.execute(); } }

Producer.java

package spring.example3; public interface Producer { String produce(); }

Consumer.java

package spring.example3; public interface Consumer { void consume(String s); }

StringConsumer.java

package spring.example3; public class StringConsumer implements Consumer { public void consume(String s){ System.out.println("DATA CONSUMED : "+s); } }

StringProducer.java

package spring.example3; public class StringProducer implements Producer { private String data="Test data "; public String produce(){ return data+" : TIME - "+new java.util.Date(); } }

producer-consumer.properties

producer.(class)=spring.example3.StringProducer
consumer.(class)=spring.example3.StringConsumer
service.(class)=spring.example3.DataService
service.producer(ref)=producer
service.consumer(ref)=consumer

No comments:

Popular Posts