[Spring] 이클립스(eclipse) XML 기반 세터/생성자 주입 (setter/constructor)

2023. 10. 23. 23:54·2023-02 몰입형 SW 정규 교육
728x90

 

 

 

 

이클립스 XML에서 세터(setter) 및 생성자(constructor) 주입 방법을 알아볼 거예요.

 

 

 

그전에 DI(Dependency Injection)에 대해 간략하게 알아보도록 하겠습니다.

DI란 쉽게 말해 의존성 주입이라고도 하는데요,

객체 간 상호작용하여 다른 객체를 참조하거나 사용하는 상태를 말합니다.

개념만 보면 어려울 것 같아서 그림을 준비했습니다.

 

 

즉, 필요할 때마다 외부에서 객체를 가져와 사용한다고 이해할 수 있습니다.

 

이해를 돕기 위해 간단한 실습을 하겠습니다.

 

 

 


 

 

 

📝 실습은 간단한 계산기로 진행하겠습니다.

 

 

 

먼저 순수 자바(Java) 코드로 작성해보겠습니다.

 

✔️ 사칙연산에 필요한 getter 및 setter를 생성합니다.

 

package com.smu.spring;

public class MyCalculation {

	Calculation calculation;
	private int firstNum;
	private int secondNum;

	public void setCalculator(Calculation calculator) {
		this.calculation = calculator;
	}

	public void add() {
		calculation.addition(firstNum, secondNum);
	}

	public void sub() {
		calculation.substraction(firstNum, secondNum);
	}

	public void mul() {
		calculation.multiplication(firstNum, secondNum);
	}

	public void div() {
		calculation.division(firstNum, secondNum);
	}

	public int getFirstNum() {
		return firstNum;
	}

	public void setFirstNum(int firstNum) {
		this.firstNum = firstNum;
	}

	public int getSecondNum() {
		return secondNum;
	}

	public void setSecondNum(int secondNum) {
		this.secondNum = secondNum;
	}
}

 

 

 

✔️ 사칙연산을 수행할 클래스를 생성합니다.

 

package com.smu.spring;

public class Calculation {

	public void addition(int f, int s) {
		System.out.println("addition: ");
		int result = f + s;
		System.out.println(f + "+" + s + "=" + result + "\n");
	}

	public void substraction(int f, int s) {
		System.out.println("substraction");
		int result = f - s;
		System.out.println(f + "-" + s + "=" + result + "\n");
	}

	public void multiplication(int f, int s) {
		System.out.println("multiplication");
		int result = f * s;
		System.out.println(f + "*" + s + "=" + result + "\n");
	}

	public void division(int f, int s) {
		System.out.println("division");
		int result = f / s;
		System.out.println(f + "/" + s + "=" + result + "\n");
	}
}

 

 

 

✔️ 메인 클래스에서 사칙연산을 실행해보겠습니다.

 

package com.smu.spring;

public class Main {

	public static void main(String[] args) {

		MyCalculation cal = new MyCalculation();
		cal.setCalculator(new Calculation());

		cal.setFirstNum(10);
		cal.setSecondNum(2);

		cal.add();
		cal.sub();
		cal.mul();
		cal.div();
	}
}

 

Java Application 실행
실행결과

 

 

 


 

 

 

📝 xml을 생성하여 외부에서 필요한 객체를 주입해보겠습니다.

 

순수 자바 코드로 작성했던 메인 클래스를 수정하겠습니다.

 

 

 

✔️ src > main > resource에 applicationCTX.xml 파일을 생성합니다.

 

recource > 우클릭 > Spring Bean Configuration File 생성

 

 

 

 

✔️ xml 파일에 Bean을 생성합니다.

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="Calculation" class="com.smu.spring.Calculation" />

	<bean id="MyCalculation" class="com.smu.spring.MyCalculation">
		<property name="calculator">
			<ref bean="Calculation" />
		</property>

		<property name="firstNum" value="10" />
		<property name="secondNum" value="2" />
	</bean>
</beans>

 

색깔이 같은 상자들끼리 이름을 맞춰서 작성하면 됩니다.

✔️ id는 변수를 설정,  property는 필드를 설정

 

 

 

✔️ MyCalculation을 불러오는 것이기 때문에 id를 동일하게 작성해야 합니다.

 

✔️ value에 값을 지정해주면 setter를 불러 사용하는 것으로 이해하시면 될 것 같습니다.

 

 

 

✔️ 수정한 메인(main) 클래스

 

package com.smu.spring;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class Main {

	public static void main(String[] args) {

		String configLocation = "classpath:applicationCTX.xml";
		AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
		MyCalculation myCalculation = ctx.getBean("MyCalculation", MyCalculation.class);

		myCalculation.add();
		myCalculation.sub();
		myCalculation.mul();
		myCalculation.div();
	}
}

 

 

 


 

 

 

📝 BMI를 이용한 예제

 

 

 

✔️ BMI getter / setter 생성

 

package com.smu.spring;

public class BMICalculator {

	private double lowWeight;
	private double normal;
	private double overWeight;
	private double obesity;
	BMICalculator bmiCalculator;

	public void bmicalculation(double weight, double height) {

		double h = height * 0.01;
		double result = weight / (h * h);

		System.out.println("BMI 지수 : " + (int) result);

		if (result > obesity) {
			System.out.println("비만 입니다.");
		} else if (result > overWeight) {
			System.out.println("과체중 입니다.");
		} else if (result > normal) {
			System.out.println("정상 입니다.");
		} else {
			System.out.println("저체중 입니다.");
		}
	}

	// 객체 주입
	public void setbmicalculation(BMICalculator bmicalculation) {
		this.bmiCalculator = bmicalculation;
	}

	public double getLowWeight() {
		return lowWeight;
	}

	public void setLowWeight(double lowWeight) {
		this.lowWeight = lowWeight;
	}

	public void setNormal(double normal) {
		this.normal = normal;
	}

	public void setOverWeight(double overWeight) {
		this.overWeight = overWeight;
	}

	public void setObesity(double obesity) {
		this.obesity = obesity;
	}
}

 

 

 

✔️ 내 신체 정보 getter / setter 생성

 

package com.smu.spring;

import java.util.ArrayList;

public class MyInfo {

	private String name;
	private double height;
	private double weight;
	private ArrayList<String> hobbys;
	private BMICalculator bmiCalculator;

	public BMICalculator getBmiCalculator() {
		return bmiCalculator;
	}

	public void setBmiCalculator(BMICalculator bmiCalculator) {
		this.bmiCalculator = bmiCalculator;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setHeight(double height) {
		this.height = height;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}

	public void setHobbys(ArrayList<String> hobbys) {
		this.hobbys = hobbys;
	}

	public void bmiCalculation() {
		bmiCalculator.bmicalculation(weight, height);
	}

	public void getInfo() {
		System.out.println("이름 : " + name);
		System.out.println("키 : " + height);
		System.out.println("몸무게 : " + weight);
		System.out.println("취미 : " + hobbys);
		bmiCalculation();
	}
}

 

 

 

✔️ xml 파일에 Bean 생성

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="BMICalculator" class="com.smu.spring.BMICalculator">
		<property name="lowWeight" value="18.5" />
		<property name="normal" value="23" />
		<property name="overWeight" value="25" />
		<property name="obesity" value="30" />
	</bean>

	<bean id="myInfo" class="com.smu.spring.MyInfo">
		<property name="bmiCalculator">
			<ref bean="BMICalculator" />
		</property>
		<property name="name" value="홍길동" />
		<property name="height" value="180" />
		<property name="weight" value="80" />
		<property name="hobbys">
			<list>
				<value>독서</value>
				<value>음악감상</value>
				<value>게임</value>
			</list>
		</property>
	</bean>

</beans>

 

 

 

✔️ 메인 클래스에서 실행

 

package com.smu.spring;

import java.util.ArrayList;
import java.util.Arrays;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class Main {

	public static void main(String[] args) {

		// BMICalculator 객체 생성 및 설정
//		BMICalculator bmiCalculator = new BMICalculator();
//		bmiCalculator.setLowWeight(18.5);
//		bmiCalculator.setNormal(23);
//		bmiCalculator.setOverWeight(25);
//		bmiCalculator.setObesity(25);

		// MyInfo 객체 생성 및 설정
//		MyInfo myInfo = new MyInfo();
//		myInfo.setName("홍길동");
//		myInfo.setHeight(180);
//		myInfo.setWeight(80);
//		myInfo.setHobbys(new ArrayList<String>(Arrays.asList("독서", "음악감상", "게임")));
//		myInfo.setBmiCalculator(bmiCalculator);

		String configLocation = "classpath:applicationCTX.xml";
		AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);
		MyInfo myInfo = ctx.getBean("myInfo", MyInfo.class);
		myInfo.getInfo();
		ctx.close();
	}
}

 

 

실행결과

 

728x90
저작자표시 비영리 변경금지 (새창열림)

'2023-02 몰입형 SW 정규 교육' 카테고리의 다른 글

[SpringBoot] 네이버 번역 API 사용하기 (파파고)  (1) 2023.12.05
[Spring] 이클립스(eclipse) annotation 사용하여 객체 주입  (2) 2023.10.24
[Spring] 이클립스(eclipse) 자바 스프링 프로젝트 생성 방법  (0) 2023.10.23
[Vue] VS Code에 Vue 프로젝트 생성  (0) 2023.09.22
HTTP 상태 코드 100 ~ 500  (0) 2023.09.21
'2023-02 몰입형 SW 정규 교육' 카테고리의 다른 글
  • [SpringBoot] 네이버 번역 API 사용하기 (파파고)
  • [Spring] 이클립스(eclipse) annotation 사용하여 객체 주입
  • [Spring] 이클립스(eclipse) 자바 스프링 프로젝트 생성 방법
  • [Vue] VS Code에 Vue 프로젝트 생성
gxxg
gxxg
함께 일하고 싶은 개발자를 꿈꾸는 예비개발자의 공부 기록
  • gxxg
    공공
    gxxg
  • 전체
    오늘
    어제
    • 분류 전체보기 (138)
      • ☁️ 구름 x 카카오 Deep Dive 풀스택 (7)
        • html, css (1)
        • Java (3)
        • 스프링 MVC (0)
      • 💻 코딩테스트 (89)
        • 백준 (2)
        • programmers (87)
      • SQLD (1)
      • Language (3)
        • Java (2)
        • JavaScript (1)
      • Style Sheet (0)
        • CSS (0)
        • SCSS & SASS (0)
      • DBMS (2)
        • Oracle (2)
        • MySQL (0)
        • postgresql (0)
        • 데이터베이스 기초 이론 (0)
      • React (0)
      • SpringBoot (0)
      • JSP (2)
      • 알고리즘 (0)
      • 2023-02 몰입형 SW 정규 교육 (24)
        • 9월 프로젝트 (8)
      • 벽돌깨기 (4)
      • Etc (4)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    DFS
    구현체
    java
    programmers
    LV3
    코테
    자바스크립트
    POST
    자바
    3단계
    프로그래머스
    2단계
    HTML
    회원 관리 시스템
    eclipse
    코딩테스트
    프로젝트 구조
    오블완
    javascript
    톰캣
    JSP
    junit 테스트
    springboot
    spring
    이클립스
    0단계
    CSS
    Lv2
    티스토리챌린지
    Lv0
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
gxxg
[Spring] 이클립스(eclipse) XML 기반 세터/생성자 주입 (setter/constructor)
상단으로

티스토리툴바