프로그래밍/Spring

스프링(Spring) - DI(Depedency Injection) 개념과 예제 : java를 이용한 설정

abfc 2016. 10. 28.
반응형

예제파일 : 

diEx3.zip


참고 : 스프링(Spring) - DI(Depedency Injection) 개념과 예제 : setter() 사용

   스프링(Spring) - DI(Depedency Injection) 개념과 예제 : 생성자 사용




이전 포스팅에서는 xml파일을 이용해 DI를 설정을 하였는데 이번 포스팅에서는 JAVA를 이용해서 DI 설정을 해보겠습니다.




이전 포스팅에서 xml파일에서 setter( )와 생성자를 이용해서 설정을 해주었던거 기억하시나요? 두가지 다 사용이 가능하다고도 했었는데 자바로 생성하면서 두가지 다 한번에 사용해보겠습니다. 비교될 xml파일에서도 두가지다 설정을 해주기 위해 수정을 해줍니다.(이전포스팅에 있는 내용과 동일한데 조금 추가되었습니다.)


applicationContext.xml




MyCats 클래스에서도 마찬가지로 변수와 setter( )를 추가해주었습니다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package diEx3;
 
import java.util.ArrayList;
 
public class MyCats {
 
    private String name;
    private int age;
    private ArrayList<String> hobbys;
    private double weight;
    private String color;
 
    
    // 생성자를 통해 name, age, hobbys를 받아와 각각의 필드의 값들을 초기화 시켜줌
    public MyCats(String name, int age, ArrayList<String> hobbys) {
        this.name = name;
        this.age = age;
        this.hobbys = hobbys;
    }
    
    public double getWeight() {
        return weight;
    }
 
    public void setWeight(double weight) {
        this.weight = weight;
    }
 
    public String getColor() {
        return color;
    }
 
    public void setColor(String color) {
        this.color = color;
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    public ArrayList<String> getHobbys() {
        return hobbys;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public void setHobbys(ArrayList<String> hobbys) {
        this.hobbys = hobbys;
    }
}
 
cs



결과를 출력해주는 메서드가 있는 Cats.java 파일도 수정해주어야겠죠?

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 diEx3;
 
 
public class Cats {
 
private MyCats myCats;
    
    //생성자를 통해 myCats를 인수로 받아와서 myCats를 초기화시켜줌
    public Cats(MyCats myCats){
        this.myCats = myCats;
    }
    
    public void getMyCatsInfo(){
        System.out.println("==============");
        System.out.println("야옹이 이름 : "+myCats.getName());
        System.out.println("야옹이 나이 : "+myCats.getAge());
        System.out.println("야옹이 취미 : "+myCats.getHobbys());
        System.out.println("야옹이 몸무게 : "+myCats.getWeight());
        System.out.println("야옹이 색 : "+myCats.getColor());
        System.out.println("==============");
    }
    
    //받아온 myCats값을 넣어줌
    public void setMyCatsInfo(MyCats myCats){
        this.myCats = myCats;
    }
 
}
 
cs




이제 setter( )와 생성자 둘 다 이용해서 JAVA에서 Bean(객체)를 생성해보겠습니다.

ApplicationContext.java 파일 생성 후 작성

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package diEx3;
 
import java.util.ArrayList;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration // 스프링 설정에 사용되는 클래스임을 명시해주는 어노테이션
public class ApplicationContext {
 
    @Bean // 객체를 생성하는 어노테이션
    public MyCats cat1(){
        
        ArrayList<String> hobbys = new ArrayList<String>();
        hobbys.add("잠자기");
        hobbys.add("꾹꾹이");
        
        MyCats myCats = new MyCats("나비",2,hobbys); //생성자
        myCats.setWeight(2.0);                     //setter()
        myCats.setColor("black");                  //setter()
        
        return myCats;                            //MyCats 객체 리턴
    }
    
    @Bean
    public MyCats cat2(){
        
        ArrayList<String> hobbys = new ArrayList<String>();
        hobbys.add("우다다");
        hobbys.add("박치기");
        
        MyCats myCats = new MyCats("호랑이",1,hobbys);
        myCats.setWeight(3.2);
        myCats.setColor("white");
        
        return myCats;
    }
    
    @Bean
    public Cats catsInfo(){
        
        Cats cats = new Cats(this.cat1());
        
        return cats;
    }
}
 
 
 
 
cs



JAVA파일에서는 어노테이션을 이용해서 객체를 생성해줍니다.

@Configuration - "이 클래스는 스프링 설정에 사용되는 클래스입니다." 라고 명시해주는 어노테이션이고,

@Bean - 객체를 생성하는 어노테이션입니다.


JAVA파일에서 설정하는 방식과 xml파일에서 설정하는 방식을 비교해보면 이렇습니다.





이제 생성한 고양이 객체를 이용해서 정보를 출력해봐야겠죠?


MainClass.java

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
32
33
34
35
36
37
38
39
40
41
package diEx3;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
 
public class MainClass {
 
    public static void main(String[] args) {
        
        /*String configLocation = "classpath:applicationContext.xml";
        
        AbstractApplicationContext ctx = 
                new GenericXmlApplicationContext(configLocation);
        
        Cats catsInfo = ctx.getBean("catsInfo",Cats.class);
        
        catsInfo.getMyCatsInfo();
        
        MyCats cat2 = ctx.getBean("cat2",MyCats.class);
        catsInfo.setMyCatsInfo(cat2);
        catsInfo.getMyCatsInfo();
        
        
        ctx.close();*/
        
        AnnotationConfigApplicationContext ctx = 
                new AnnotationConfigApplicationContext(ApplicationContext.class);
        
        Cats catsInfo = ctx.getBean("catsInfo",Cats.class);
        catsInfo.getMyCatsInfo();
        
        MyCats cat2 = ctx.getBean("cat2",MyCats.class);
        catsInfo.setMyCatsInfo(cat2);
        catsInfo.getMyCatsInfo();
        
        ctx.close();
        
    }
 
}
 
cs



JAVA파일에서는 어노테이션을 이용해서 bean을 설정해주었기 때문에 xml에서 설정해주었을때 객체를 가져오기 위해 사용했던 클래스가 아닌 AnnotationConfigApplicationContext 클래스를 이용하여 context를 불러옵니다.

이전에 사용했던 GenericXmlApplicationContext 클래스에서 파생된 클래스이기 때문에 JAVA파일도 결국 내부적으로 xml로 변환이 된다고 하네요.



실행결과)


잘 나오나요? xml이든 java파일이든 본인 스타일에 맞춰서 사용을 해도되는데 java파일은 잘 사용하지 않는다고 하네요. 그냥 보기에도 xml이 더 깔끔해보이기도 하고요. 그런데 스프링부트에서는 대부분 java파일에서 설정해준다는 거....!


**

3개의 포스팅을 통해서 스프링 DI설정을 알아봤습니다. 꼭 직접 소스코드를 작성해보셔서 본인의 것으로 만드시길 바랍니다~!








반응형

댓글

💲 추천 글