Dependency Injection: Setter Injection

di-img2
This is an example of Setter injection, which is most popular method compared to field and constructor injection. A business logic class uses a object of DAO service class.
di-setter-3
di-setter-inj-rma
This is annotation based DI, so you don’t need to specify a bean in XML file but you still need to tell annotation drive to servlet context.

<annotation-driven />
<context:component-scan base-package="com.ns.spring" />

As the line 20 to 24 shows, it will injects the dependency via a setter method. And 28 to 39 shows it usage.

package com.ns.spring.common;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ns.spring.constant.RtrnConstant;
import com.ns.spring.model.RMA_HDR;
import com.ns.spring.model.ui.RmaHdrModel;
import com.ns.spring.service.template.RmaHdrService;

@Component
public class RmaBL implements RtrnConstant {

	private static RmaHdrService hdrSvc;

	@Autowired(required = true)
	public void setHdrSvc(RmaHdrService hdrSvc) {
		this.hdrSvc = hdrSvc;
	}

	public static List<Object[]> getRmaHdrListObj(String rmaNum) {
		return hdrSvc.getListRmaHdrBySql(rmaNum);
	}

	public static RMA_HDR saveHdr(RmaHdrModel rma, HttpServletRequest req) {
		RMA_HDR obj = new RMA_HDR(rma);
		if (rma.getId() == 0) {
			hdrSvc.save(obj);
			// Set RMA# with formatted
			DecimalFormat df = new DecimalFormat("000000");
			obj.setRmaNum("RMA" + df.format((double) obj.getId()));
		}
		hdrSvc.update(obj);
		req.getSession().removeAttribute(CONST.HDR_LIST.getVal());
		return obj;
	}

	public static RMA_HDR getRmaHdrObj(String rmaNum) {
		List<Object[]> rmaHdrList = getRmaHdrListObj(rmaNum);
		if (!CommonBL.isEmpty(rmaHdrList)) {
			Object[] objArr = rmaHdrList.get(0);
			int id = (Integer) objArr[0];
			return hdrSvc.findById(id);
		}
		return null;
	}
.
.
.
}

Dependency Injection: Field Injection

di-img2
This is a example of field injection, which is very simple. One controller use three different service classes to access data base (DAO service class).
di-fld-3
di-filed-inj-rp-rsn
This is annotation based DI, so you don’t need to specify a bean in XML file but you still need to tell annotation drive to servlet context.

<annotation-driven />
<context:component-scan base-package="com.ns.spring" />

Line 42 to 48 shows the field injection, and 65 to 94 use the object without “new” keyword.

package com.ns.spring;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ns.spring.common.CommonBL;
import com.ns.spring.common.RmaBL;
import com.ns.spring.common.RsnBL;
import com.ns.spring.common.TpBL;
import com.ns.spring.common.TpRsnBL;
import com.ns.spring.common.gen.BLFactory;
import com.ns.spring.constant.RtrnConstant;
import com.ns.spring.model.RTRN_RSN;
import com.ns.spring.model.RTRN_TP;
import com.ns.spring.model.RTRN_TP_RSN_CMBN;
import com.ns.spring.model.ui.RmaHdrModel;
import com.ns.spring.model.ui.RtrnRsnModel;
import com.ns.spring.model.ui.RtrnTpModel;
import com.ns.spring.service.template.RtrnRsnService;
import com.ns.spring.service.template.RtrnTpRsnService;
import com.ns.spring.service.template.RtrnTpService;

@Controller
public class TpRsnController implements RtrnConstant {

	@Autowired(required = true)
	private RtrnTpService tpSvc;

	@Autowired(required = true)
	private RtrnRsnService rsnSvc;

	@Autowired(required = true)
	private RtrnTpRsnService tpRsnSvc;

	@RequestMapping(value = "/cUrlValAttrbMain01Jsp", params = "goToTpRsn", method = RequestMethod.POST)
	public ModelAndView goToTpRsn(ModelMap model, HttpServletRequest req) {
		return getMVSubTpRsn01(model, req);
	}

	@RequestMapping(value = "/cUrlValAttrbSubTpRsn01Jsp", params = "backToRmaFromTpRsn", method = RequestMethod.POST)
	public ModelAndView backToRmaFromTpRsn(Model model, HttpServletRequest req) {
		return getMVMain01(req);
	}

	@RequestMapping(value = "/cUrlValAttrbSubTpRsn01Jsp", params = "toBoundRsnList", method = RequestMethod.POST)
	public ModelAndView toBoundRsnList(@ModelAttribute("RtrnTpModel") RtrnTpModel tp, ModelMap model, HttpServletRequest req) {

		String tpSelected = (String) req.getSession().getAttribute(CONST.TP_SELECTED.getVal());
		if (CommonBL.hasValue(tpSelected)) {
			RTRN_TP tpObj = this.tpSvc.findById(tpSelected);
			if (tpObj != null) {
				List<String> selectedCheckBox = TpRsnBL.getRsnToBound(tp, req);
				if (!CommonBL.isEmpty(selectedCheckBox)) {
					Set<RTRN_RSN> rtrnRsns = new HashSet<RTRN_RSN>();
					for (String code : selectedCheckBox) {
						RTRN_RSN rsnObj = this.rsnSvc.findById(code);
						if (rsnObj != null) {
							rtrnRsns.add(rsnObj);
							tpObj.setRtrnRsns(rtrnRsns);
							this.tpSvc.saveOrUpdate(tpObj);
						}
					}
				}
			}
		}
		return getMVSubTpRsn01(model, req);
	}

	@RequestMapping(value = "/cUrlValAttrbSubTpRsn01Jsp", params = "toUnBoundRsnList", method = RequestMethod.POST)
	public ModelAndView toUnBoundRsnList(@ModelAttribute("RtrnTpModel") RtrnTpModel tp, ModelMap model, HttpServletRequest req) {

		String tpSelected = (String) req.getSession().getAttribute(CONST.TP_SELECTED.getVal());
		if (CommonBL.hasValue(tpSelected)) {
			List<String> selectedCheckBox = tp.getSelectedCheckBox();
			if (!CommonBL.isEmpty(selectedCheckBox)) {
				for (String code : selectedCheckBox) {
					RTRN_TP_RSN_CMBN tpRsnObj = this.tpRsnSvc.getTpRsnCmbnByHql(tpSelected, code);
					if (tpRsnObj != null) {
						this.tpRsnSvc.delete(tpRsnObj);
					}
				}
			}
		}
		return getMVSubTpRsn01(model, req);
	}

.
.
.

}

Static Factory Pattern

design-pattern-hdr_img2
It is always good to use Design Pattern in your application, although it is not required, in order to avoid spaghetti. One of popular design pattern is Factory pattern. The concept is similar to DI (Dependency Injection). In this example, I use Static Factory pattern.
stat-facto-pattern-diagram1
With Factory pattern, you can instantiate a class with “new” (Source Code)

@RequestMapping("/cUrlValSubLine01Jsp/{rmaNum}")
public ModelAndView goToSubLine01Jsp(@PathVariable("rmaNum") String rmaNum,	Model model, HttpServletRequest req) {
	List<RmaLineModel> rmaLineModelList = RmaDtlBL.getRmaLineListWithCdTblNm(rmaNum, null);
	return getMVSubLine01(rmaNum, rmaLineModelList, req);
}

This method is being called to set ModelAndView object, and one of them is the list of code for auto-complete feature

private ModelAndView getMVSubLine01(String rmaNum, List<RmaLineModel> rmaLinsList, HttpServletRequest req) {

	RmaLineListModel newModel = new RmaLineListModel(rmaNum, rmaLinsList);

	ModelAndView modelAndView = new ModelAndView(VIEW.SUB_LINE_01.getVal());
	modelAndView.addObject(CONST.FORM_KEY.getVal(), newModel);
	// For item detail list
	modelAndView.addObject(CONST.LINE_LIST_MODEL.getVal(), newModel);
	// Setup Status drop down line the item list
	modelAndView.addObject(CONST.HDR_STS_LIST.getVal(), getList(CONST.HDR_STS_LIST.getVal()));
	// Item list for AJAX Auto complete
	req.getSession().setAttribute(CONST.MDSE_LIST.getVal(), getList(CONST.MDSE_LIST.getVal()));
	return modelAndView;
}

Above line 12 calls this method:

private List<?> getList(String key) {
	BLFactory fact = BLFactory.getInstance(key);
	return fact.getList();
}

Above line 12 calls this method:

package com.ns.spring.common.gen;

import java.util.List;

import com.ns.spring.constant.RtrnConstant;

public class BLFactory implements RtrnConstant {

	private BLService svc;

	private BLFactory(String param) {
		if (CONST.HDR_STS_LIST.getVal().equals(param)) {
			this.svc = new RtrnCommonBL();
		} else if (CONST.TP_LIST.getVal().equals(param)) {
			this.svc = new TpCommonBL();
		} else if (CONST.MDSE_LIST.getVal().equals(param)) {
			this.svc = new MdseCommonBL();
		}
	}

	// static factory
	public static BLFactory getInstance(String param) {
		return new BLFactory(param);
	}

	public List<?> getList() {
		return this.svc.getList();
	}
}

This factory class returns static instance via interface BLService.

package com.ns.spring.common.gen;

import java.util.List;

public interface BLService {
	public List<?> getList();
}
package com.ns.spring.common.gen;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ns.spring.common.CommonBL;
import com.ns.spring.constant.RtrnConstant.CONST;
import com.ns.spring.model.MDSE;
import com.ns.spring.model.RMA_HDR_STS;
import com.ns.spring.model.RTRN_TP;
import com.ns.spring.model.ui.MdseModel;
import com.ns.spring.model.ui.RmaHdrStsModel;
import com.ns.spring.model.ui.RtrnTpModel;
import com.ns.spring.service.template.MdseService;
import com.ns.spring.service.template.RmaHdrStsService;
import com.ns.spring.service.template.RtrnTpService;

@Component
public class MdseCommonBL implements BLService {

	private static MdseService mdseSvc;
	
	@Autowired(required = true)
	public void setMdseSvc(MdseService mdseSvc) {
		this.mdseSvc = mdseSvc;
	}

	@Override
	public List<MdseModel> getList() {
		List<MdseModel> mdseModelList = new ArrayList<>();
		List<MDSE> mdseList = mdseSvc.findAll();
		if (!CommonBL.isEmpty(mdseList)) {
			for (int i = 0; i < mdseList.size(); i++) {
				MDSE obj = (MDSE) mdseList.get(i);
				mdseModelList.add(new MdseModel(i, obj.getMdseCd()));
			}
		}
		return mdseModelList;
	}
}

getList() eventually calls findAll() that returns all record from MDSE table.