1일(08.17) DI
📂 DI : dependency injection
- DI : 객체(Bean)간의 의존 관계를 외부의 파일(스프링 설정 파일)에서 설정하겠다.
- 의존주입(injection) 생성자를 통한주입, setter통한 주입 방법이 있다.
- Bean : 클래스로부터 생성된 객체를 스프링에서 빈이라고 한다.
- 스프링 설정 파일: Bean을 관리한다. 기본 파일 명은 applicationContext.xml 이다.
-BeanFactory (interface)
: 빈을 생성하고 설정, 관리하는 역할 수행
getBean() 메서드를 지원한다.
가장 일반적으로 많이 사용하는 클래스는 XmlBeanFactory 이다.
💾 package sample1
Point.java
package sample1;
public class Point {
private double xpos; //3.0
private double ypos;
//다른 클래스에서 사용하고 싶다면 setter, getter를 완성한다.
public double getXpos() {
return xpos;
}
public void setXpos(double xpos) {
this.xpos = xpos;
}
public double getYpos() {
return ypos;
}
public void setYpos(double ypos) {
this.ypos = ypos;
}
}
Circle.java
package sample1;
public class Circle {
private Point point;
private double radius;
public Circle(Point point, double radius) {
super();
this.point =point;
this.radius =radius;
}
public void display() {
System.out.println("원의 중심:"+point.getXpos()+","+point.getYpos());
System.out.println("원의 면적:"+getArea());
}
public double getArea() {
return Math.pow(radius, 2.0)*Math.PI;
}
}
원의 중심 좌표, 반지름 정보를 넣고싶다.
private double xpos; -원의 중심좌표
private double ypos; -원의 중심좌표 , point클래스와 변수가 같으므로 포함시키는 작업을 한다.
private Point point; - Point타입을 멤버로 받아서 point변수를 상속받아서 xpos,ypos를 포함시킨다.
Main.java
package sample1;
public class Main {
public static void main(String[] args) {
/* 실행시킬때 java application 으로 실행한다! */
Point point = new Point();
point.setXpos(3.0); //3.0을 넘긴다.
point.setYpos(4.0);
Circle circle = new Circle(point, 10.0); //10.0 반지름 정보
//circle 변수가 관리하는 곳에 멤버변수 2개가 있다.
//point에는 값이 들어간 xpos=3.0, ypos=4.0 가 있다.
circle.display(); //메서드를 호출하여 출력한다.
}
}
💾 package sample2
Point.java
package sample2;
public interface Point {
public double getXpos();
public void setXpos(double xpos);
public double getYpos();
public void setYpos(double ypos);
}
PointImpl.java
package sample2;
public class PointImpl implements Point{
//인터페이스를 사용하면 덜 의존적으로 프로그래밍을 할 수 있다.
private double xpos; //setter를 통한 주입
private double ypos;
@Override
public double getXpos() {
return xpos;
}
@Override
public void setXpos(double xpos) {
this.xpos = xpos;
}
@Override
public double getYpos() {
return ypos;
}
@Override
public void setYpos(double ypos) {
this.ypos = ypos;
}
}
Circle.java
package sample2;
public interface Circle {
public void display();
public double getArea();
}
CircleImpl.java
package sample2;
public class CircleImpl implements Circle{
private Point point; //생성자를 통한 주입(injection)
private double radius;
public CircleImpl(Point point, double radius) {
super();
this.point = point;
this.radius = radius;
}
@Override
public void display() {
System.out.println("원의 중심: "+point.getXpos()+","+ point.getYpos());
System.out.println("원의 면적: "+getArea());
}
@Override
public double getArea() {
return Math.pow(radius, 2.0)*Math.PI;
}
}
Main.java
package sample2;
public class Main {
public static void main(String[] args) {
Point point = new PointImpl();//자식을 부모가 관리할수있도록 부모인 Point사용해도 된다.
point.setXpos(3.0);
point.setYpos(4.0);
Circle circle = new CircleImpl(point,10.0);//객체를 만들고 ,point set으로 주입
circle.display();
}
}
//DI : dependency injection 의존 주입
💾 package sample3
Point.java
package sample3;
public interface Point {
public double getXpos();
public void setXpos(double xpos);
public double getYpos();
public void setYpos(double ypos);
}
PointImpl.java
package sample3;
public class PointImpl implements Point{
private double xpos;
private double ypos;
@Override
public double getXpos() {
return xpos;
}
@Override
public void setXpos(double xpos) {
this.xpos = xpos;
}
@Override
public double getYpos() {
return ypos;
}
@Override
public void setYpos(double ypos) {
this.ypos=ypos;
}
}
Circle.java
package sample3;
public interface Circle {
public void display();
public double getArea();
}
CircleImpl.java
package sample3;
public class CircleImpl implements Circle{
private Point point;
private double radius;
public CircleImpl(Point point, double radius) {
super();
this.point = point;
this.radius = radius;
}
@Override
public void display() {
System.out.println("원의 중심 : " + point.getXpos() + "," + point.getYpos());
System.out.println("원의 면적 : " + getArea());
}
@Override
public double getArea() {
return Math.pow(radius, 2.0) * Math.PI;
}
}
Main.java
package sample3;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
/*
Point point = new PointImpl();
point.setXpos(3.0);
point.setYpos(4.0);
Circle circle = new CircleImpl(point,10.0);
circle.display();
*/
/* XML파일에서 객체를 생성한다.
* XML파일을 만들어서 setter와 생성자 객체를 주입해본다
*/
//resource는 xml파일이 있는 곳을 관리하는 변수이다.
Resource resource= new ClassPathResource("appContex.xml");//xml 파일에 접근하기 위하여 xml파일 이름을 적어준다.
//Bean을 만드는 공장 , XML파일에 설정한대로 Bean을 생성해라
BeanFactory factory = new XmlBeanFactory(resource);//XmlBeanFactory의 부모가 BeanFactory이다. 부모BeanFactory가 관리한다.
//Point point = PointImpl 객체, object를 리턴하므로 Point로 다운캐스팅을 해준다.
Point point = (Point)factory.getBean("point"); //getBean안에는 xml파일에 작성된 bean의 id속성의 값이 들어간다.
System.out.println(point.getXpos()+","+point.getYpos());
//CircleImpl circle = new CircleImpl 객체
Circle circle = (Circle)factory.getBean("circle");//factory가 관리하는 또다른 bean circle
circle.display();
//circle변수의 display메서드를 호출하여 원의 중심과 원의 면적을 출력해볼 수 있다.
}
}
//DI : dependency injection -의존주입 생성자를 통한주입, setter통한 주입 방법이 있다.
//sample2가 덜 의존적으로 프로그래밍 한것이다.
XML파일에서 객체를 생성한다.
* XML파일을 만들어서 setter와 생성자 객체를 주입을 해보았다.
Resource resource = new ClassPathResource("appContext.xml");
- xml 파일에 접근하기 위하여 xml파일 이름을 적어준다.
- resource는 xml파일이 있는 곳을 관리하는 변수이다.
BeanFactory factory = new XmlBeanFactory(resource);
- Bean을 만드는 공장 , XML파일에 설정한대로 Bean을 생성해라
- XmlBeanFactory의 부모가 BeanFactory이다. 부모BeanFactory가 관리한다.
Point point = (Point)factory.getBean("point");
= Point point =PointImpl();
- object를 리턴하므로 Point로 다운캐스팅을 해준다.
- getBean안에는 xml파일에서 id속성의 값이 들어간다.
Circle circle = (Circle)factory.getBean("circle");
- CircleImpl circle = new CircleImpl 객체
- factory가 관리하는 또다른 bean circle
- circle.display(); : circle변수의 display메서드를 호출하여 원의 중심과 원의 면적을 출력해볼 수 있다.
- 스프링 설정 파일: Bean을 관리한다. 기본 파일 명은 applicationContext.xml 이다.
- BeanFactory (interface)
- 빈을 생성하고 설정, 관리하는 역할 수행
- getBean() 메서드를 지원한다.
- 가장 일반적으로 많이 사용하는 클래스는 XmlBeanFactory 이다.
appContext.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">
<!-- sample3.PointImpl point = new sample3.PointImpl();
point.setXpos(3.0)
point.setYpos(4.0)
-->
<bean class="sample3.PointImpl" id="point">
<property name="xpos">
<value type="double">3.0</value>
</property>
<property name="ypos">
<value type="double">4.0</value>
</property>
</bean>
<!--
CircleImpl circle = new CircleImpl(point, 10.0); //객체를 만들고 ,point set으로 주입
circle.display(); -->
<bean class="sample3.CircleImpl" id="circle">
<constructor-arg>
<ref bean="point"></ref>
</constructor-arg>
<constructor-arg>
<value type="double">10.0</value>
</constructor-arg>
</bean>
</beans>
✔ xml 생성 방법
프로젝트 클릭 - src/main/resources- 마우스 우클릭- new - other - spring폴더 - Spring Bean Configuration file
-next - 자동으로 resources 선택이 되어있고, file이름을 적어준다 - finish
<beens> 안에 작성한다.(객체생성하는 작업)
<bean></bean> : 멤버를 변수로 받는 어떤 클래스의 객체를 만들겠다. 객체 안에서 setter메서드 형성한다.
<property name=""></property> :bean안에 작성,setter메서드 주입할때 사용한다. set은 안적혀있지만.
<bean class="sample3.CircleImpl" id="circle">
<constructor-arg> :생성자 주입한다.
<ref bean="point"></ref> : 객체를 주입할때 ref를 사용한다.
</constructor-arg>
<constructor-arg>
<value type="double">10.0</value> : 값을 넣을때는 value를 사용한다.
</constructor-arg>
</bean>