Monday, November 3, 2014

Java via constructor



How to get spring application context object reference

package com.java2novice.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware
{
 private static ApplicationContext context;
 public ApplicationContext getApplicationContext()
{
        return context;
 }
 public void setApplicationContext(ApplicationContext ac)throws BeansException
{
        context = ac;
    }
}

Spring java based configuration Import

package com.java2novice.test;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.java2novice.bean.MyBusinessService;
import com.java2novice.bean.MyJdbcService;
import com.java2novice.config.MyAppConfig;
public class SpringDemo
{
public static void main(String a[])
{
 SuppressWarnings("resource")
        ApplicationContext context =
                new AnnotationConfigApplicationContext(MyAppConfig.class);
        MyJdbcService jdbc = (MyJdbcService) context.getBean("jdbcService");
        jdbc.createJdbcConnection();
        MyBusinessService busServ = (MyBusinessService) context.getBean("bussService");
        busServ.runMyBusiness();
    }
}

Spring Dependency Injection via setter method

package com.java2novice.test;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.bean.ColorManager;
public class DiSetterDemo
{
public static void main(String a[])
{
        SuppressWarnings("resource")
        ApplicationContext context
          = new ClassPathXmlApplicationContext("applicationContext.xml");
        ColorManager clrManager = (ColorManager)context.getBean("colorManager");
        clrManager.pringColor();
    }
}

Spring Dependency Injection via Constructor

package com.java2novice.test;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.bean.ColorManager;
public class DiConstructorDemo
{
 public static void main(String a[])
{
   SuppressWarnings("resource")
   ApplicationContext context = new    ClassPathXmlApplicationContext("applicationContext.xml");
ColorManager clrManager = (ColorManager)context.getBean("colorManager");
        clrManager.pringColor();
    }
}

Constructor overloading issue with spring constructor based injection

package com.java2novice.bean;
public class Article
{
   private String title;
    private int number;
    private String body;
 public Article(String title, int number)
{
        this.title = title;
        this.number = number;
  }
  public Article(String title, String body)
  {
        this.title = title;
        this.body = body;
    }
}

No comments:

Post a Comment