DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ratn has posted 5 posts at DZone. View Full User Profile

Setting Up Spring Created Beans In Non Spring Created POJO

06.05.2010
| 4755 views |
  • submit to reddit
        Sometime we have to set up Spring created beans in simple non container created bean .

lets consider that we have to develop an application for creating invoices .
It has to be integrated with different front end systems.And each front-end has different way to create invoices .

Lets have a generic interface - 
 public interface CreateInvoice(){
     public Invoice create();
 }

Now a concrete implementation - 
  public classs CreateInvoiceForTwoDates implements CreateInvoice{
       private Date fromDate ;
       private Date toDate;
       //Spring container created bean 
       @Autowired
       private InvoiceItemRepository invoiceItemRepository;

       public CreateInvoiceForTwoDates(Date fromDate,Date toDate){
             this.fromDate = fromDate;
             this.toDate = toDate;
       }
      public Invoice create(){
          invoiceItemRepositoty.getInvoiceItem(fromDate,toDate);
          //other code
      }
  }

now lets have a factory to create Invoice --
       public class SimpleInvoiceFactory  {
        @Autowired
        org.springframework.beans.factory.config.AutowireCapableBeanFactory beanFactory;

        public createInvoice(InvoiceCreationCriteria criteria){
           CreateInvoiceForTwoDates creatInvoiceForTwoDates = 
           new CreateInvoiceForTwoDates(criteria.fromDate,criteria.toDate);
           
           //Now to set spring created bean InvoiceItemRepository into creatInvoiceForTwoDates
           //we have to do 
           beanFactory.autowire(creatInvoiceForTwoDates);
           creatInvoiceForTwoDates.create();
        }

       }