씨네
공부하는 개발자 강씨네
씨네
  • 분류 전체보기 (460)
    • Web (21)
      • HTML (11)
      • CSS (10)
    • JS 관련 (49)
      • JavaScript (27)
      • JQuery (22)
    • TS 관련 (15)
      • TypeScript (15)
    • NodeJS (7)
      • NodeJS (7)
    • 따라하며 배우는 시리즈 (23)
      • NodeJS & ReactJS Basic (23)
      • NodeJS & ReactJS Movie (0)
      • NodeJS & ReactJS Youtube (0)
      • NodeJS & ReactJS ChatBot (0)
    • SPA (14)
      • React (14)
      • Vue (0)
      • Anguler (0)
    • Java 관련 (118)
      • Java (52)
      • JDBC (6)
      • JSP & Servlet (18)
      • Spring Legecy (38)
      • SpringBoot (4)
    • Python (26)
      • Python (20)
      • PyMongo (1)
      • Django (5)
    • Git (24)
      • Github (24)
    • RDB (22)
      • Oracle (21)
      • MySQL (1)
    • NoSQL (5)
      • MongoDB (5)
    • OS (4)
      • Linux (4)
    • 빅데이터 (2)
      • hadoop (2)
    • IDE (20)
      • eclipse (11)
      • VSCODE (4)
      • VisualStudio (1)
      • IntelliJ (1)
      • PyCharm (1)
      • DBeaver (2)
    • Install (3)
      • Tomcat (1)
      • Docker (1)
      • Anaconda (1)
    • 오류&에러 (28)
      • TS (2)
      • NodeJS (7)
      • SQL (8)
      • Java (1)
      • Spring (4)
      • Git (6)
      • 기타 (0)
    • 알고리즘 (67)
      • 수열 (1)
      • 백준(backjoon) (39)
      • Programmers (27)
    • 자격증 (5)
      • SQLD (5)
    • 기타 (2)
    • IT유튜브로 지식쌓기 (2)

공지사항

인기 글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
씨네

공부하는 개발자 강씨네

[Spring] DI / IoC (Bean 객체 생성_02) - 생성자 주입
Java 관련/Spring Legecy

[Spring] DI / IoC (Bean 객체 생성_02) - 생성자 주입

2022. 3. 11. 11:58
728x90

패키지 구조

​

MessageBean.java

package com.test01;

public interface MessageBean {
	
	public void sayHello();

}

​

MessageBeanImpl.java

package com.test01;

public class MessageBeanImpl implements MessageBean {
	
	private String fruit;
	private int cost;
	
	public MessageBeanImpl() {
		this.fruit = "바나나";
		this.cost = 5000;
	}

	public MessageBeanImpl(String fruit, int cost) {
		this.fruit = fruit;
		this.cost = cost;
	}

	@Override
	public void sayHello() {
		System.out.printf("과일 : %s \t 가격 : %d \n", fruit, cost);
	}

}

​

applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- 기본생성자 호출 -->
	<bean id="banana" class="com.test01.MessageBeanImpl"></bean>
	
	<!-- constructor->생성자 arg->아규먼트 -->
	<bean id="strawberry" class="com.test01.MessageBeanImpl">
		<constructor-arg>
			<value>딸기</value>
		</constructor-arg>
		<constructor-arg>
			<value>6000</value>
		</constructor-arg>
	</bean>
	
	<bean id="kiwi" class="com.test01.MessageBeanImpl">
		<constructor-arg value="키위"></constructor-arg>
		<constructor-arg value="7000"></constructor-arg>
	</bean>
	
	<bean id="cherry" class="com.test01.MessageBeanImpl">
		<constructor-arg index="1" value="8000"></constructor-arg>
		<constructor-arg index="0" value="체리"></constructor-arg>
	</bean>
</beans>

​

MTest.java

package com.test01;

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

public class MTest {

	public static void main(String[] args) {
		ApplicationContext factory = new ClassPathXmlApplicationContext("com/test01/applicationContext.xml");
		
		MessageBean banana = (MessageBean) factory.getBean("banana");
		MessageBean strawberry = (MessageBean) factory.getBean("strawberry");
		MessageBean kiwi = (MessageBean) factory.getBean("kiwi");
		MessageBean cherry = (MessageBean) factory.getBean("cherry");
		
		banana.sayHello();
		strawberry.sayHello();
		kiwi.sayHello();
		cherry.sayHello();
	}
}

​

실행결과

​

위의 코드에서 저희가 봐야할 개념은 applicationContext.xml안의 bean객체입니다.

​

applicationContext.xml에서

<!-- 기본생성자 호출 -->
<bean id="banana" class="com.test01.MessageBeanImpl"></bean>

<!-- MessageBean banana = new MessageBeanImpl(); -->

해당 객체는 MessageBeanImpl에서 기본생성자를 호출하게 됩니다.

객체의 id는 banana라고 주었네요.

MessageBeanImpl.java에서 기본생성자를 호출하게되면

public MessageBeanImpl() {
	this.fruit = "바나나";
	this.cost = 5000;
}

해당 생성자가 호출됩니다.

해당 생성자에서 과일 이름을 바나나라고 주었네요.

​

​

​

<!-- constructor->생성자 arg->아규먼트 -->
<bean id="strawberry" class="com.test01.MessageBeanImpl">
	<constructor-arg>
		<value>딸기</value>
	</constructor-arg>
	<constructor-arg>
		<value>6000</value>
	</constructor-arg>
</bean>

<!-- MessageBean strawberry = new MessageBeanImpl("딸기", 6000); -->

해당 객체는 MessageBeanImpl에서 파라미터가 String, int 형식으로 각각씩 2개있는 생성자를 호출하게 됩나다.

여기에서 <constructor-arg>는 생성자 / 아규먼트를 뜻합니다.

​

public MessageBeanImpl(String fruit, int cost) {
	this.fruit = fruit;
	this.cost = cost;
}

해당 메소드가 호출되면서 파라미터로 "딸기"와 6000이 들어오게 됩니다.

​

​

​

<bean id="kiwi" class="com.test01.MessageBeanImpl">
	<constructor-arg value="키위"></constructor-arg>
	<constructor-arg value="7000"></constructor-arg>
</bean>

해당 객체는 <constructor-arg>의 속성으로 value를 넣을수 있다는 것을 보여줍니다. 마찬가지로 파라미터 2개 짜리 생성자가 호출됩니다.

​

​

​

<bean id="cherry" class="com.test01.MessageBeanImpl">
	<constructor-arg index="1" value="8000"></constructor-arg>
	<constructor-arg index="0" value="체리"></constructor-arg>
</bean>

해당 객체는 index의 순서도 정해줄수 있습니다.

​

​

이렇게 xml파일에서 생성된 bean객체들을 MTest에서 호출하는 과정입니다.

MessageBean banana = (MessageBean) factory.getBean("banana");
MessageBean strawberry = (MessageBean) factory.getBean("strawberry");
MessageBean kiwi = (MessageBean) factory.getBean("kiwi");
MessageBean cherry = (MessageBean) factory.getBean("cherry");

객체가 넘어올때는 Object타입으로 넘어오기 때문에 반드시 형변환을 해주어야합니다.

​

banana.sayHello();
strawberry.sayHello();
kiwi.sayHello();
cherry.sayHello();

객체의 메서드를 호출하면 주입되었던 값들이 호출이 잘 되겠죠??

​


다음번 예제를 보겠습니다.

​

패키지 구조

​

Address.java

package com.test02;

public class Address {

	private String name;
	private String addr;
	private String phone;

	public Address(String name, String addr, String phone) {
		this.name = name;
		this.addr = addr;
		this.phone = phone;
	}

	@Override
	public String toString() {
		return "Address [name=" + name + ", addr=" + addr + ", phone=" + phone + "]";
	}
	
}

​

applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="lee" class="com.test02.Address">
		<constructor-arg name="name" value="이순신"></constructor-arg>
		<constructor-arg name="addr" value="서울시 강남구"></constructor-arg>
		<constructor-arg name="phone" value="010-1111-1111"></constructor-arg>
	</bean>
	
	<bean id="hong" class="com.test02.Address">
		<constructor-arg name="name" value="홍길동"></constructor-arg>
		<constructor-arg name="addr" value="경기도 수원시"></constructor-arg>
		<constructor-arg name="phone" value="010-2222-2222"></constructor-arg>
	</bean>

</beans>

​

MTest.java

package com.test02;

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

public class MTest {
	public static void main(String[] args) {
		ApplicationContext factory = new ClassPathXmlApplicationContext("com/test02/applicationContext.xml");
		
		Address lee = (Address) factory.getBean("lee");
		Address hong = (Address) factory.getBean("hong");
		
		System.out.println(lee);
		System.out.println(hong);
	}

}

실행결과

​

​

해당코드에서는 index의 값 대신에 파라미터 이름을 주입해주었습니다.

생성자에 있는 파라미터 변수의 이름을 말합니다.

	<bean id="lee" class="com.test02.Address">
		<constructor-arg name="name" value="이순신"></constructor-arg>
		<constructor-arg name="addr" value="서울시 강남구"></constructor-arg>
		<constructor-arg name="phone" value="010-1111-1111"></constructor-arg>
	</bean>

lee라는 이름으로 Address에 있는 생성자를 호출합니다.

파라미터가 Sring타입이 3개가 있는 생성자를 호출하게됩니다.

아규먼트로는 name에는 "이순신", addr에는 "서울시 강남구", phone에는 "010-1111-1111"을 주입합니다.

​

 

<bean id="hong" class="com.test02.Address">
	<constructor-arg name="name" value="홍길동"></constructor-arg>
	<constructor-arg name="addr" value="경기도 수원시"></constructor-arg>
	<constructor-arg name="phone" value="010-2222-2222"></constructor-arg>
</bean>

마찬가지로 hong이라는 이름의 객체를 만드는데 Address에서 파라미터 3개짜리 생성자를 호출합니다.

아규먼트로는 name에는 "홍길동", addr에는 "경기도 수원시", phone에는 "010-2222-2222"을 주입합니다.

​

실행 결과에서는 toString을 override했기 때문에 객체를 호출결과는 위의 실행결과 같이 나옵니다.


패키지 구조

​

Person.java

package com.test03;

public class Person {
	
	private String name;
	private int age;
	
	public Person() {
		
	}
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public void sayHello() {
		System.out.printf("내가 좋아하는 걸그룹 %s 은(는) 평균나이는 %d 살 입니다. \n", name, age);
	}

}

​

applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="best" class="com.test03.Person">
		<constructor-arg name="name" value="라붐"></constructor-arg>
		<constructor-arg index="1" value="25"></constructor-arg>
	</bean>
</beans>

​

MTest.java

package com.test03;

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

public class MTest {
	
	public static void main(String[] args) {
		ApplicationContext factory = new ClassPathXmlApplicationContext("com/test03/applicationContext.xml");
		
		Person bf = (Person) factory.getBean("best");
		bf.sayHello();
	}

}

실행결과

​

해당 코드에서는 constructor-arg태그에서 name속성과 index속성을 섞어서 넣었습니다.

<bean id="best" class="com.test03.Person">
	<constructor-arg name="name" value="라붐"></constructor-arg>
	<constructor-arg index="1" value="25"></constructor-arg>
</bean>

이와 같이 섞어서 넣을수도 있습니다.

생성자의 파라미터 변수가 name인 파라미터에는 라붐이라는 값을 아규먼트로 넣어주고 index가 1인 파라미터에는 25라는 아규먼트를 넣어줍니다.

728x90

'Java 관련 > Spring Legecy' 카테고리의 다른 글

[Spring] DI / IoC (Bean 객체 생성_04) - Singleton  (0) 2022.03.13
[Spring] DI / IoC (Bean 객체 생성_03) - setter 주입  (0) 2022.03.12
[Spring] DI / IoC (Bean 객체 생성_01)  (0) 2022.03.10
[Spring] 기본세팅(Maven / pom.xml)  (0) 2022.03.09
[Spring] Spring FrameWork(스프링이란?, 스프링의 특징)  (0) 2022.03.08
    'Java 관련/Spring Legecy' 카테고리의 다른 글
    • [Spring] DI / IoC (Bean 객체 생성_04) - Singleton
    • [Spring] DI / IoC (Bean 객체 생성_03) - setter 주입
    • [Spring] DI / IoC (Bean 객체 생성_01)
    • [Spring] 기본세팅(Maven / pom.xml)
    씨네
    씨네
    개발자 씨네가 공부하는 내용을 기록 겸 공유하는 블로그입니다!

    티스토리툴바