3. spring 기본-2

2017. 7. 26. 21:20· FrameWork/spring
반응형
SMALL

공격하는 방식을 바꾸는데 클래스를 따로 만들고 다른 타입의 객체를 만들거야


WeaponImpl2 클래스를 만들어




1
2
3
4
5
6
7
8
9
10
11
12
package test.mypac;
 
public class WeaponImpl2 implements Weapon{
 
    @Override
    public void attack() {
        System.out.println("변칙 공격을 해요!");
        
    }
 
}
 
Colored by Color Scripter
cs


메인 클래스를 수정하지 않고 이 객체의 attack 라는 곳에 실행 순서가 들어오가 할수 있음


xml 문서를 수정하면 됌.


1
2
3
4
5
6
7
8
9
10
11
<?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">
 
    <!-- new WeaponImpl() 한 객체의 참조값을 myWeapon 이라는 아이디로 관리하기 -->
 
    <bean id="myWeapon" class="test.mypac.WeaponImpl2"></bean>
    
</beans>
 
Colored by Color Scripter
cs


이렇게 수정해 주면 됌.


Spring 은 이거에서 부터 시작



메인이 하나의 객체라면

그 객체에 의존하고 있는 다른 클래스도 수정할 필요가 없어


필요한 객체를 사용하지 않고 인터페이스를 사용하는 것을 봐야해


의존관계를 느슨하게 하기 위해서


이렇게 하는 것







핵심객체를 직접 만들지 않고, 어디에선가 관리하게 만들어 놓고, 거기에서 받아서 쓰는 구조




메인 클래스 하나 더 만들어서


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package test.main;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import test.mypac.Weapon;
 
public class MainClass2 {
    public static void main(String[] args) {
        ApplicationContext context=
                new ClassPathXmlApplicationContext("test/main/init.xml");
        
        Weapon w1=(Weapon)context.getBean("myWeapon");
        Weapon w2=(Weapon)context.getBean("myWeapon");
        
        if(w1==w2){
            System.out.println("w1 과 w2 는 같아요");
        }else{
            System.out.println("w1 과 w2 는 달라요");
        }
    }
}
Colored by Color Scripter
cs


이렇게 코딩후 실행 해 보면



같다고 출력되는 것을 볼 수 있어


여러번 가져와도 참조값이 같다는 얘기는

getBean 할때마다 객체를 생성하지 않는 다는 얘기

하나만 생성하고 id가 myWeapon 이라는 것을 가져온다는 것을 알수 있다.



Car와 Engine 클래스를 만들고


Car 클래스는


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package test.mypac;
 
public class Car {
    // 맴버필드
    private String company;
    private Engine engine;
    
    public void setCompany(String company) {
        this.company = company;
    }
    
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
    
    // 달리는 메소드
    public void drive(){
        System.out.println("부릉~부릉~ 자동차가 달려요~!");
    }
}
 
Colored by Color Scripter
cs

이렇게 코딩해 주고



달리는 메소드를 호출할때는 xml 을 이용할거야


test.main2 패키지와 그 하위에 init.xml 만들어주


1
2
3
4
5
6
7
8
9
<?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="car1" class="test.mypac.Car"></bean>
    
</beans>
 
Colored by Color Scripter
cs

init.xml 코드



MainClass 만들어서


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package test.main2;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import test.mypac.Car;
 
public class MainClass {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("test/main2/init.xml");
        
        Car car1=(Car)context.getBean("car1");
    }
}
 
Colored by Color Scripter
cs


이렇게 코딩해 주고


init.xml 에

1
2
3
4
5
6
7
8
9
10
11
<?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="car1" class="test.mypac.Car"></bean>
    
    <bean id="car2" class="test.mypac.Car"></bean>
    
</beans>
 
Colored by Color Scripter
cs

car2 bean 추가생성


이렇게 해주고 MainClass로 가서 car2를 추가해 준후 비교 해보면??


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package test.main2;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import test.mypac.Car;
 
public class MainClass {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("test/main2/init.xml");
        
        Car car1=(Car)context.getBean("car1");
        
        Car car2=(Car)context.getBean("car2");
        
        if(car1==car2){
            System.out.println("car1과 car2는 참조값이 같아요!");
        }else{
            System.out.println("car1과 car2는 참조값이 달라요!");
        }
    }
}
 
Colored by Color Scripter
cs


메인 클래스에 이렇게 소스코드를 추가해 준후 실행해보면 알수 있어!!



참조값이 다르다고 나옴


SpringBeanContainer 에 객체의 아이디 값을 다르게 해놓고

가져와서 참조값이 다르다고 나온 것.


Car 클래스로 가서

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
package test.mypac;
 
public class Car {
    // 맴버필드
    private String company;
    private Engine engine;
    
    public void setCompany(String company) {
        this.company = company;
    }
    
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
    
    // 달리는 메소드
    public void drive(){
        
        System.out.println("자동차의 제조사는 :"+company);
        
        if(engine==null){
            System.out.println("Engine 객체가 없어서 못달려요!");
            return;
        }
        
        System.out.println("부릉~부릉~ 자동차가 달려요~!");
    }
}
 
Colored by Color Scripter
cs

제조사와 engine 객체 조건문을 추가해주고

MainClass 로 가서 car1,2 를 비교해 보면

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
31
package test.main2;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import test.mypac.Car;
 
public class MainClass {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("test/main2/init.xml");
        
        Car car1=(Car)context.getBean("car1");
        
        Car car2=(Car)context.getBean("car2");
        
        if(car1==car2){
            System.out.println("car1과 car2는 참조값이 같아요!");
        }else{
            System.out.println("car1과 car2는 참조값이 달라요!");
        }
        
        car1.drive();
        
        System.out.println("----------------------------");
        
        car2.drive();
        
    }
}
 
Colored by Color Scripter
cs
이렇게 코딩해서 실행해



필요한 멤버필드의 내용이 없기에 제대로 동작을 안하는 것을 볼수 있어

이제 그걸 추가해 줄거야

init.xml 로 가서

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="car1" class="test.mypac.Car"></bean>
    
    <bean id="car2" class="test.mypac.Car">
        <property name="company" value="현대자동차"></property>
    </bean>
    
</beans>
 
Colored by Color Scripter
cs



이렇게 코딩해주고 다시 실행해 보면



car2는 제조사가 null이 아닌 것을 볼수 있어



car2 에 engine 도 넣어주고 싶은데



이렇게 넣을때 넣을수 있는 것이 문자나 숫자뿐이 안돼...


근데 engine 은 engine 타입이야


그래서 engine 객체가 있어야해


init.xml에


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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">
    <!-- Engine 객체 -->
    <bean id="myEngine" class="test.mypac.Engine"></bean>
    
    <bean id="car1" class="test.mypac.Car"></bean>
    
    <bean id="car2" class="test.mypac.Car">
        <property name="company" value="현대자동차"></property>
        <property name="engine" ref="myEngine"></property>
    </bean>
    
</beans>
 
Colored by Color Scripter
cs

Engine 객체 추가해주고


참조값을 넣을때에는 value가 아닌 ref로 넣어줘



이제 MainClass 로가서 다시 실행해 보면


car2가 잘 달리는 것을 볼수 있어


xml 문서를 JAVA 코드로 바꾸면


이렇게 되는 것과 마찬가지임




value로 초록색과 핑크색이 들어가는 것이고



ref 는 Spring Bean Container 에서 관리 하고 있는 객체중 하나를 넣어줄때 사용


car1은 조립을 못한거고

car2는 조립을 잘 한거라고 느끼면 됌




반응형
LIST

'FrameWork > spring' 카테고리의 다른 글

4. Step01_Hello  (0) 2017.07.26
3. spring 기본 - 3  (0) 2017.07.26
3. Spring 기본  (0) 2017.07.25
2. maven 설치 이후 프로젝트 만들기전에 할 설정 들  (0) 2017.07.25
1. maven 설치  (0) 2017.07.25
'FrameWork/spring' 카테고리의 다른 글
  • 4. Step01_Hello
  • 3. spring 기본 - 3
  • 3. Spring 기본
  • 2. maven 설치 이후 프로젝트 만들기전에 할 설정 들
- 광속거북이 -
- 광속거북이 -
IT관련 일하면서 공부 및 일상 에 관한 내용들을 기록하기 위한 블로그 입니다.
누리IT관련 일하면서 공부 및 일상 에 관한 내용들을 기록하기 위한 블로그 입니다.
- 광속거북이 -
누리
- 광속거북이 -
전체
오늘
어제
  • 카테고리 (457)
    • 구글문서 (4)
    • 설치방법들 (3)
    • FrameWork (73)
      • Django (6)
      • Python (32)
      • AngularJS (13)
      • spring (21)
    • Programing (61)
      • JAVA (11)
      • etc... (2)
      • 오류 해결 (29)
      • Algorithm (5)
    • Front-End (25)
      • CSS (3)
      • html (6)
      • javascript (10)
      • vueJS (5)
    • Back-End (5)
      • 리눅스 (12)
      • PostgreSQL (14)
      • MySQL (2)
      • Shell (1)
      • docker (1)
      • GIT (1)
    • Util (9)
      • BIRT (2)
      • JMeter (3)
      • MobaXterm Personal (1)
      • ClipReport (2)
    • 이클립스 설정 (10)
      • SVN (1)
    • 업무중 기록해둘 것들... (1)
    • 영화 (8)
    • etc.. (199)
      • 여행 (25)
      • AI (1)
      • 문화생활 (3)
      • tistory (3)
      • 글, 생각 (4)
      • 먹을 곳 (29)
      • issue (4)
      • 결혼 (1)
      • 가족여행기록 (1)
      • Tip (51)
      • 강아지 (5)
      • 일기 (0)
      • 게임 (3)
      • 주식 (7)
      • 코로나19 (7)
      • 맥북 (5)
    • 비공개 (0)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 설치
  • 맛집
  • 백준
  • IntelliJ
  • 삼성증권
  • VSCode
  • 윈도우10
  • 해지
  • tomcat
  • 리눅스
  • 합정
  • PostgreSQL
  • 연천
  • 제주도
  • 설정
  • 이클립스
  • 포켓몬고
  • 카페
  • Java
  • 인텔리제이

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
- 광속거북이 -
3. spring 기본-2
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.