프로그래밍/Spring & Spring boot

06 Spring : Setter 메소드 / 생성자를 통한 의존성 주입 방법

pupu91 2022. 9. 1. 18:35
반응형

 

 

 

< 의존 관계인 bean 만들기 >

 

인터페이스 생성

package com.greedy.section02.xmlconfig;

public interface Account {
	잔액 조회
	String getBalance();
	입금
	String deposit(int money);
	출금
	String withDraw(int money);
	
}

 

 

상속받는 class 생성

package com.greedy.section02.xmlconfig;

public class PersonalAccount implements Account{ 

	private int backCode;
    private String accNo;
    private String accPwd;
    private int balance;
    
    public PersonalAccount(int bankCode, String accNo, String accPwd) {
    	sper();
        this.bankCode = bankCode;
		this.accNo = accNo;
		this.accPwd = accPwd;
    }
    
    public PersonalAccount(int bankCode, String accNo, String accPwd, int balance) {
		super();
		this.bankCode = bankCode;
		this.accNo = accNo;
		this.accPwd = accPwd;
		this.balance = balance;
	}

	@Override
	public String getBalance() {
		
		return this.accNo + " 계좌의 현재 잔액은 " + this.balance + "원 입니다.";
	}

	@Override
	public String deposit(int money) {
		
		String str = "";
		
		if(money >= 0) {
			this.balance += money;
			str = money + "원이 입금되었습니다.";
		} else {
			str = "금액을 잘못 입력하셨습니다.";
		}
		return str;
	}

	@Override
	public String withDraw(int money) {
		
		String str = "";
		
		if(this.balance >= money) {
			this.balance -= money;
			str = money + "원이 출금되었습니다.";
		} else {
			str = "잔액이 부족합니다. 잔액을 확인해주세요.";
		}
		return str;
	}
}

 

 

 

< DTO 생성 >  

: 필드에 private 인터페이스명 지어줄이름; 선언

package com.greedy.section02.xmlconfig;

public class MemberDTO {

	private int sequence;
	private String name;
	private String phone;
	private String email;
	private Account personalAccount;
	
	public MemberDTO() {}

	public MemberDTO(int sequence, String name, String phone, String email, Account personalAccount) {
		super();
		this.sequence = sequence;
		this.name = name;
		this.phone = phone;
		this.email = email;
		this.personalAccount = personalAccount;
	}

	public int getSequence() {
		return sequence;
	}

	public void setSequence(int sequence) {
		this.sequence = sequence;
	}

	public String getName() {
		return name;
	}

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

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Account getPersonalAccount() {
		return personalAccount;
	}

	public void setPersonalAccount(Account personalAccount) {
		this.personalAccount = personalAccount;
	}

	@Override
	public String toString() {
		return "MemberDTO [sequence=" + sequence + ", name=" + name + ", phone=" + phone + ", email=" + email
				+ ", personalAccount=" + personalAccount + "]";
	}

	
	
}

 

 

 


 

1. setter 메소드를 통한  의존성 주입방법

 

xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
    bean 태그의 클래스 속성은 인터페이스 타입이 아닌 구현 클래스 타입으로 작성
    <bean id="accountGenerator" class="com.greedy.section02.xmlconfig.PersonalAccount">
		<constructor-arg index="0" value="20"/>
		<constructor-arg index="1" value="110-234-567890"/>
		<constructor-arg index="2" value="1234"/>
	</bean>
    
    setter 주입
    	<bean id="memberGenerator" class="com.greedy.section02.xmlconfig.MemberDTO">
		<!-- 각각의 필드에 대한 setter메서드를 호출해서 작성해라! -->
		<property name="sequence" value="1"/>
		<property name="name" value="홍길동"/>
		<property name="phone" value="010-1234-5678"/>
		<property name="email" value="hong123@gmail.com"/>
		<property name="personalAccount" ref="accountGenerator"></property>
        =>연결해줄 클래스는 value가 아닌 ref=빈id로 설정해야한다.
	
	</bean>
 </beans>

 

 

 

 

 

java

@Configuration
public class ContextConfiguration2 {

    @Bean
	public Account accountGenerator() {
		return new PersonalAccount(20, "110-234-567890", "1234"); 
	}
	
	 setter 메소드를 사용한 의존성 주입
	@Bean
	public MemberDTO memberGenerator() {
		
		MemberDTO member = new MemberDTO();
		member.setSequence(2);
		member.setName("홍길동");
		member.setPhone("010-2485-5678");
		member.setEmail("hong123@gmail.com");
		member.setPersonalAccount(accountGenerator()); 
		
		return member;
	}	
}

 

 

2.  생성자를 통한 의존성 주입 방법

 

xml

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

	<bean id="accountGenerator" class="com.greedy.section02.xmlconfig.PersonalAccount">
		<constructor-arg index="0" value="20"/>
		<constructor-arg index="1" value="110-234-567890"/>
		<constructor-arg index="2" value="1234"/>
	</bean>
	 
        <bean id="memberGenerator" class="com.greedy.section02.xmlconfig.MemberDTO">
		<constructor-arg name="sequence" value="1"/>
		<constructor-arg name="name" value="홍길동"/>
		<constructor-arg name="phone" value="010-1234-5678"/>
		<constructor-arg name="email" value="hong123@gmail.com"/>
		<constructor-arg>
			<ref bean="accountGenerator"/> 
		</constructor-arg>
	</bean> -->

 

 

java

 

package com.greedy.section01.javaconfig.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.greedy.section01.javaconfig.Account;
import com.greedy.section01.javaconfig.MemberDTO;
import com.greedy.section01.javaconfig.PersonalAccount;

@Configuration
public class ContextConfiguration {
	
	@Bean
	public Account accountGenerator() {
		
        return new PersonalAccount(20, "110-234-567890", "1234"); 
	}
	
	
	@Bean
	public MemberDTO memberGenerator() {
		
		return new MemberDTO(1, "홍길동", "010-1234-5678", "hong123@gmail.com", accountGenerator()); 
        
	}	
}

 

 

 

< 출력하기 >

package com.greedy.section02.xmlconfig;

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

public class Application {
	public static void main(String[] args) {
    
		ApplicationContext context = new GenericXmlApplicationContext("com/greedy/section02/xmlconfig/config/spring-context.xml");
		
		MemberDTO member = context.getBean(MemberDTO.class);
		
        System.out.print(member.getName()+"님의");
		System.out.println(member.getPersonalAccount().getBalance()); 
		System.out.println(member.getPersonalAccount().deposit(10000));
		System.out.println(member.getPersonalAccount().getBalance());
		System.out.println(member.getPersonalAccount().withDraw(3000));
		System.out.println(member.getPersonalAccount().getBalance());
	
	}
}
출력 결과

홍길동님의110-234-567890 계좌의 현재 잔액은 0원 입니다.
10000원이 입금되었습니다.
110-234-567890 계좌의 현재 잔액은 10000원 입니다.
3000원이 출금되었습니다.
110-234-567890 계좌의 현재 잔액은 7000원 입니다
반응형