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;
	}
.
.
.
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.