잡동사니에도 사랑을

[21.11.09] (Chapter02 - sample02 / 03 / 04) 본문

SPRING

[21.11.09] (Chapter02 - sample02 / 03 / 04)

luvforjunk 2021. 11. 9. 09:40
728x90
반응형

[문제1]

Project : chapter02

Package : sample02

Interface : Calc.java

추상Method : public void calculate();

Class : HelloSpring - main()

             CalcAdd.java

             CalcMul.java

 

[실행결과]

25 + 36 = xx

→ xml에서 CalcAdd를 빈(add)으로 Constructor Injection

 

25 * 36 = xx

→ xml에서 CalcMul를 빈(mul)으로 Setter Injection

 

 

////////Calc.java

package sample02;

public interface Calc {
	public void calculate(); // 추상메소드
	// Overiding해주기 위해 add와 mul이 들어온다.
}

 

 

 

 

////////CalcAdd.java

package sample02;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@AllArgsConstructor
// 모든 인자를 사용하여
public class CalcAdd implements Calc {
	private int num1, num2;

	/*
	 * public CalcAdd(int num1, int num2) { super(); this.num1 = num1; this.num2 =
	 * num2; }
	 */

	@Override
	public void calculate() {
		System.out.println(num1 + "+" + num2 + "=" + (num1 + num2));
	}
}

 

 

 

 

////////CalcMul.java

package sample02;

import lombok.Setter;

public class CalcMul implements Calc {
	@Setter
	private int num1, num2;

	/*
	 * public void setNum1(int num1) { this.num1 = num1; }
	 * 
	 * 
	 * 
	 * public void setNum2(int num2) { this.num2 = num2; }
	 */

	@Override
	public void calculate() {
		System.out.println(num1 + "*" + num2 + "=" + (num1 * num2));
	}

}

 

 

 

////////HelloSpring.java

package sample02;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

		// 형 변환 (1)
		Calc calc;
		calc = (Calc) context.getBean("calcAdd");
		calc.calculate();
		
		// 형 변환 (2)
		calc = context.getBean("calcMul", Calc.class);
		calc.calculate();

		/*
		// 생성자 이용
		CalcAdd calcAdd = new CalcAdd(25, 36);

		// setter 이용
		CalcMul calcMul = new CalcMul();
		calcMul.setNum1(25); // xml에서 property name="" 에는 메소드명이 들어가야 하는데, setNum1이 곧 메소드명이다
		calcMul.setNum2(36);
		*/
	}
}

 

 

 

/////////applicationContext.xml

<!-- 중략 -->
<!-- sample02 -->
	<bean id="calcAdd" class="sample02.CalcAdd">
		<constructor-arg>
			<value>25</value>
		</constructor-arg>
		<constructor-arg value="36">
		</constructor-arg>
	</bean>

	<bean id="calcMul" class="sample02.CalcMul">
		<property name="num1">
			<value>25</value>
		</property>
		<property name="num2" value="36">
		</property>
	</bean>

 


 

 

 

[문제2]

applicationContext.xml에서 이름, 국어, 영어, 수학의 데이터를 SungJukDTO.java에 주입하기

SungJukImpl.java 에서는 SungJukDTO.java를 이용하여 총점, 평균을 계산하시오

XML를 통해서 데이터 주입하시오

 

Project : chapter02

Package : sample03

Class : HelloSpring - main()

Interface : SungJuk.java

추상Method : public void calcTot();//총점 계산

             public void calcAvg();//평균 계산

             public void display();//출력

             public void modify();//수정

 

Class : SungJukImpl.java - Constructor Injection

 

Class : SungJukDTO.java - Setter Injection

             name, kor, eng, math, tot, avg

             

[실행결과]

이름 국어영어수학 총점 평균

홍길동 9710095xxxxx.xx

 

* 수정 - modify()에서 처리

이름 입력 : 코난

국어 입력 : 100

영어 입력 : 100

수학 입력 : 95

 

이름 국어 영어 수학 총점 평균

코난 100 100 95 xxx xx.xx

 

 

////////SungJuk.java

package sample03;

public interface SungJuk {
	public void calcTot();// 총점 계산
	public void calcAvg();// 평균 계산
	public void display();// 출력
	public void modify();// 수정
}

 

 

 

////////SungJukDTO.java

package sample03;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
// annotation 걸어주기 - 무수히 많은 set get을 잡지 않아도 잡아져있음
public class SungJukDTO {
	private String name;
	private int kor, eng, math, tot;

	private double avg;

	public String toString() {
		return name + "\t" + kor + "\t" + eng + "\t" + math + "\t" + tot + "\t" + String.format("%.2f", avg);
	}
}

 

 

 

////////SungJukImpl.java

package sample03;

import java.util.Scanner;

import lombok.AllArgsConstructor;

@AllArgsConstructor
// 아래 내용을 생성해주는 것 대신 @AllArgsConstrutor 걸어주면 됨.
public class SungJukImpl implements SungJuk {

	private SungJukDTO sungJukDTO;

//	public SungJukImpl(SungJukDTO sungJukDTO) {
//		this.sungJukDTO = sungJukDTO;
//	}

	@Override
	public void calcTot() {
		sungJukDTO.setTot(sungJukDTO.getKor() + sungJukDTO.getEng() + sungJukDTO.getMath());
	}

	@Override
	public void calcAvg() {
		sungJukDTO.setAvg(sungJukDTO.getTot() / 3.0);
	}

	@Override
	public void display() {
		System.out.println("이름\t국어\t영어\t수학\t총점\t평균");
		System.out.println(sungJukDTO); // 클래스명@16진수 값으로 나옴
	}

	@Override
	public void modify() {
		Scanner scan = new Scanner(System.in);
		System.out.print("이름 입력 : ");
		sungJukDTO.setName(scan.next());
		System.out.print("국어 입력 : ");
		sungJukDTO.setKor(scan.nextInt());
		System.out.print("영어 입력 : ");
		sungJukDTO.setEng(scan.nextInt());
		System.out.print("수학 입력 : ");
		sungJukDTO.setMath(scan.nextInt());
	}

}

 

 

 

 

////////HelloSpring.java

package sample03;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		SungJuk sungJuk = (SungJuk) context.getBean("sungJukImpl");
		sungJuk.calcTot();
		sungJuk.calcAvg();
		sungJuk.display();
		System.out.println();
		
		System.out.println(" *** 수정 *** ");
		sungJuk.modify();
		sungJuk.calcTot();
		sungJuk.calcAvg();
		sungJuk.display();
		System.out.println();
	}
}

 

 

 

////////applicationContext.xml

<!-- 중략 -->
<!-- sample03 -->
	<bean id="sungJukDTO" class="sample03.SungJukDTO">
		<property name="name" value="홍길동" />
		<property name="kor" value="97" />
		<property name="eng" value="100" />
		<property name="math" value="95" />
	</bean>

	<bean id="sungJukImpl" class="sample03.SungJukImpl">
		<constructor-arg ref="sungJukDTO"></constructor-arg>
		<!-- id="sungJukDTO"를 참조한다는 뜻 -->
	</bean>

 


 

 

Project : chapter02

Package : sample04

Interface : MessageBean.java

Class : MessageBeanImpl.java

           HelloSpring.java - main()

 

Interface : Outputter.java

Class : FileOutputter.java - 파일로 출력

 

 

////////MessageBean.java

package sample04;

public interface MessageBean {
	public void helloCall();
}

 

 

 

////////MessageBeanImpl.java

package sample04;

public class MessageBeanImpl implements MessageBean {
	private String name;
	private String phone;
	private Outputter outputter;

	public MessageBeanImpl() {
		System.out.println("MessageBeanImpl 기본 생성자");
	}

	public MessageBeanImpl(String name) {
		System.out.println("1 MessageBeanImpl 생성자");
		this.name = name;
	}

	public void setPhone(String phone) {
		System.out.println("4 setPhone(String phone)");
		this.phone = phone;
	}

	public void setOutputter(Outputter outputter) {
		System.out.println("5 setOutputter(Outputter outputter)");
		this.outputter = outputter;
	}

	@Override
	public void helloCall() {
		outputter.output("이름 = " + name + ", 핸드폰 = " + phone);
	}
}
// 생성자 다음에 ref을 먼저 수행하고 순서대로 setter를 불러낸다.
// 이런 걸 life cycle이라 한다. 순서를 잘 파악하는 것이 핵심
// 생성자 처리 -> 레퍼런스 처리 -> 세터 처리

 

 

 

////////Outputter.java

package sample04;

public interface Outputter {
	public void output(String message);
}

 

 

 

////////FileOutputter.java

package sample04;

import java.io.FileWriter;
import java.io.IOException;

public class FileOutputter implements Outputter {
	private String filePath, fileName;

	// Setter Injection
	public void setFilePath(String filePath) {
		System.out.println("2 setFilePath(String filePath)");
		this.filePath = filePath;
	}

	public void setFileName(String fileName) {
		System.out.println("3 setFileName(String fileName)");
		this.fileName = fileName;
	}

	@Override
	public void output(String message) {
		try {
			FileWriter fileWriter = new FileWriter(filePath + fileName);
			fileWriter.write(message);
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

 

 

////////HelloSpring.java

package sample04;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpring {

	public static void main(String[] args) {
		System.out.println("Life Cycle");
		System.out.println();
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		MessageBean bean = context.getBean("messageBeanImpl2", MessageBean.class);		
		bean.helloCall();
	}
}

 

 

 

////////applicationContext.xml

<!-- 중략 -->
	<!-- sample04 -->
	<bean id="messageBeanImpl2" class="sample04.MessageBeanImpl">
		<constructor-arg value="홍길동" />
		<property name="phone" value="010-123-1234" />
		<property name="outputter" ref="fileOutputter" />
	</bean>

	<bean id="fileOutputter" class="sample04.FileOutputter">
		<property name="filePath" value="D:/Spring/" />
		<property name="fileName" value="result.txt" />
	</bean>
</beans>

 

728x90
반응형

'SPRING' 카테고리의 다른 글

[21.11.11] (sample03 - chapter02_SpringMaven)  (0) 2021.11.11
[21.11.10]  (0) 2021.11.09
[21.11.09] (Chapter02 - sample02)  (0) 2021.11.09
[21.11.08] (Chapter02)  (0) 2021.11.08
[21.11.08] (chapter01)  (0) 2021.11.08