일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- 항해99 #항해플러스 #주니어개발자 #주니어개발자역량강화 #주니어개발자멘토링 #개발자사이드프로젝트 #코딩부트캠프 #코딩부트캠프후기
- #
- 국비지원#국비교육#국비지원자바#국비교육자바#css#HTML#JAVA
- db#데이터베이스#오라클#sql
- Java#java#자바#다오#디티오#브이오#dao#dto#vo
- Java#컴파일러#자바컴파일러#
- 국비지원JAVA#국비지원자바#프로그랭#JSP#국비지원JSP#국비교육JSP#웹개발자#코딩
- Java#JAVA#매개변수
- 국비지원JAVA
- 국비지원자바#국비교육자바#국비지원java#국비교육java#자바스크립트#프론트엔드
- 자바#Java#배열예시#연습#기초다지기
- 개발자도서#개발자책#도메인#DDD#도메인주도개발시작하기#개발스터디#
- Spring#spring#스프링#스프링프레임워크#스프링의존성주입#스프링생성자#스프링기본#국비지원#국비교육#국비지원스프링
- IntelliJ#인텔리제이#인텔리#단축키
- Spring#spring#스프링#스프링프레임워크#스프링자동주입#스프링생성자#스프링기본#국비지원#국비교육#국비지원스프링
- tibero#티베로#이중화#failvover
- 국비지원#국비교육
- Java#정처기#비트연산자#정보처리기사
- 자바
- 국비지원JAVA#국비교육JAVA#국비지원자바#국비교육자바#JSP#SERVLET#서블릿#
- Java#java#메모리영역#클래스로더#가비지컬렉터
- #java#JAVA#프로그래밍#웹개발자
- 개발자#it도서#도메인#DDD#ddd
- html#HTML#프론트엔드#개발자#코딩#국비지원#국비교육#국비지원프론트엔드#국비지원HTML#국비지원html#국비프론트엔드
- 프로그래밍
- spring#Spring#RequestBody#ResponseBody
- 항해플러스#항해#항해플러스3기#회고
- java
- Resource #
- 쿼리스트링#쿼리문자열#바인딩
Archives
- Today
- Total
개린이 개발노트
[Spring] 스프링 생성자를 통한 주입 의존성 주입(Dependency Injection) 본문
728x90
의존성 주입(Dependency Injection)
의존성 주입은 Spring에서 아주 중요한 개념이자 장점
bean객체 생성시 bean 객체가 관리할 값이나 객체를 주입하는 것을 의미
bean 객체 생성 후 bean 객체가 가질 기본값을 자바코드로 설정하는 것이 아닌 bean을 정의하는
xml코드에서 정의하는 개념
Bean을 정의할 때 constructor-arg 태그를 이용해 주입하게 되면 생성자를 통해 주입할 수 있음.
Bean 객체를 생성할 때 객체의 기본값을 생성자를 통해 주입가능.
package sanghoon.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sanghoon.beans.DataBean;
import sanghoon.beans.TestBean;
import sanghoon.beans.TestBean2;
public class MainClass {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("sanghoon/config/beans.xml");
TestBean t1= new TestBean();
t1.printData();
System.out.println("-------------------");
TestBean t2= new TestBean(100);
t2.printData();
System.out.println("-------------------");
TestBean t3= new TestBean(11.11);
t3.printData();
System.out.println("-------------------");
TestBean t4 = new TestBean("문자열");
t4.printData();
System.out.println("-------------------");
TestBean t5 = new TestBean(200,22.22,"안녕하세요");
t5.printData();
System.out.println("-------------------");
// TestBean t6 = new TestBean("반갑습니다",300,33.33);
// t6.printData(); -> TestBean클래스의 생성자에 정의되어있는 매개변수의 순서가 일치하지 않기때문에 에러가남
/*TestBeanClass 이용 ↑*/
/*beans.xml 이용 ↓ */
TestBean obj1 = ctx.getBean("obj1",TestBean.class);
obj1.printData();
System.out.println("-------------------");
TestBean obj2 = ctx.getBean("obj2",TestBean.class);
obj2.printData();
System.out.println("-------------------");
TestBean obj3 = ctx.getBean("obj3",TestBean.class);
obj3.printData();
System.out.println("-------------------");
TestBean obj4 = ctx.getBean("obj4",TestBean.class);
obj4.printData();
System.out.println("-------------------");
TestBean obj5 = ctx.getBean("obj5",TestBean.class);
obj5.printData();
TestBean obj6 = ctx.getBean("obj6",TestBean.class);
obj6.printData();
// beans.xml에 만들어져있는 매개변수의 순서와 달라도 정상적으로 출력됨 (자바와의 차이)
TestBean obj7 = ctx.getBean("obj7",TestBean.class);
obj7.printData();
System.out.println("-------------------");
//자바코드로 할때
DataBean d1= new DataBean();
DataBean d2= new DataBean();
TestBean2 t200 = new TestBean2(d1, d2);
t200.printData();
//beans.xml로 할 때
System.out.println("-------------------");
TestBean2 obj8 = ctx.getBean("obj8",TestBean2.class);
obj8.printData();
System.out.println("-------------------");
TestBean2 obj9 = ctx.getBean("obj9", TestBean2.class);
obj9.printData();
ctx.close();
}
}
package sanghoon.beans;
public class TestBean {
private int data1;
private double data2;
private String data3;
public TestBean() {
System.out.println("TestBean의 기본 생성자");
this.data1=0;
this.data2=0.0;
this.data3=null;
}
public TestBean(int data1) {
System.out.println("TestBean의 생성자: int 변수 1개");
this.data1=data1;
this.data2=0.0;
this.data3=null;
}
public TestBean(double data2) {
System.out.println("TestBean의 생성자: double 변수 1개");
this.data1=0;
this.data2=data2;
this.data3=null;
}
public TestBean(String data3) {
System.out.println("TestBean의 생성자: String 변수1개");
this.data1=0;
this.data2=0.0;
this.data3=data3;
}
public TestBean(int data1, double data2, String data3) {
System.out.println("TestBean의 생성자: String 변수3개");
this.data1=data1;
this.data2=data2;
this.data3=data3;
}
public void printData() {
System.out.printf("data1 : %d\n", data1);
System.out.printf("data2 : %f\n", data2);
System.out.printf("data3 : %s\n", data3);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sanghoon</groupId>
<artifactId>ConstructorDI</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- xml에서 사용할 속성들 -->
<properties>
<!-- 자바 버전 -->
<java-vesion>1.8</java-vesion>
<!-- 스프링 버전 -->
<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
<!-- <org.springframework-version>4.3.25.RELEASE</org.springframework-version> -->
<org.slf4j-version>1.7.26</org.slf4j-version>
<ch.qos.logback-version>1.2.3</ch.qos.logback-version>
</properties>
<!-- 프로젝트에서 사용할 라이브러리 정보 -->
<dependencies>
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- slf4j -->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<!-- logback -->
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback-version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
<?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='obj1' class='sanghoon.beans.TestBean' lazy-init='true' />
<bean id='obj2' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='100' type='int'/>
</bean>
<bean id='obj3' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='11.11' type='double'/>
</bean>
<bean id='obj4' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='문자열'/>
</bean>
<bean id='obj5' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='200' type='int'/>
<constructor-arg value='22.22' type='double'/>
<constructor-arg value='안녕하세요' type='java.lang.String'/>
</bean>
<bean id='obj6' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='반갑습니다' type='java.lang.String'/>
<constructor-arg value='300' type='int'/>
<constructor-arg value='33.33' type='double'/>
</bean>
<bean id='obj7' class='sanghoon.beans.TestBean' lazy-init='true'>
<constructor-arg value='44.44' type='double' index='1'/>
<constructor-arg value='4' type='int' index='0'/>
<constructor-arg value='반갑습니다' type='java.lang.String' index='2'/>
</bean>
<bean id='obj8' class='sanghoon.beans.TestBean2' lazy-init='true'>
<constructor-arg>
<bean class='sanghoon.beans.DataBean'/>
</constructor-arg>
<constructor-arg>
<bean class='sanghoon.beans.DataBean'/>
</constructor-arg>
</bean>
<!--주입할 때 마다 자동으로 객체생성하려고 scope='prototype' 설정했음!! -->
<bean id='data_bean' class='sanghoon.beans.DataBean' scope='prototype'/>
<bean id='obj9' class='sanghoon.beans.TestBean2' lazy-init='true'>
<constructor-arg ref= 'data_bean'/>
<constructor-arg ref='data_bean'/>
</bean>
</beans>
package sanghoon.beans;
public class TestBean2 {
private DataBean data1;
private DataBean data2;
public TestBean2(DataBean data1,DataBean data2) {
this.data1= data1;
this.data2= data2;
}
public void printData() {
System.out.printf("data1 : %s\n", data1);
System.out.printf("data2 : %s\n", data2);
}
}
package sanghoon.beans;
public class DataBean {
}
728x90
'스프링Spring' 카테고리의 다른 글
[Spring] 스프링 Spring Framework 컬렉션 주입 (0) | 2023.01.15 |
---|---|
[Spring] 스프링 Setter 메서드를 통한 주입 (0) | 2023.01.15 |
[Spring] 스프링 BeanPostProcessor (0) | 2023.01.12 |
[Spring] 스프링 빈(bean) 객체의 생명주기 (0) | 2023.01.10 |
[Spring] 스프링 빈(bean) 객체 생성하는 법 (0) | 2023.01.07 |