새소식

[5분 내로] 강의실/📋 Spring Annotation이란?

[Spring] ModelAttribute, RequestParam, Autowired, Resource란?

  • -
728x90

3. @ModelAttribute = 파라미터 To VO

- 용어 정리 : '파라미터를 받아서 VO에 맵핑'하라는 어노테이션

- 사용 예제 : public String testMethod(@ModelAttribute UserVO userVo)

- 사용 예제 해석 : 파라미터로 들어오는 값들을 한방에 UserVO에 맵핑해주세요.
 
ex) UserVO.java
public class UserVO{
private String id;
private String name;
 
public test(String id, String name){
this.id = id;
this.name = name;
}
 
public String getId(){
return id;
}
}

 

4. @RequestParam = 파라미터 To 변수

- 용어 정리 : '파라미터를 변수에 저장'하는 어노테이션

- 사용 예제 : @RequestParam("userId") String id

- 사용 예제 해석 : 'userId'라는 파라미터를 받아서 'id'라는 변수에 저장하세요.

 

5. @Autowired = 자동 주입

- 용어 정리 : 스프링에게 '객체를 자동으로 생성'하라고 시키는 어노테이션

- 용어 상세 설명 : 

의존하는 객체를 자동으로 삽입해주며 생성자, 필드(=전역변수), 메서드 세 곳에 적용이 가능.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Test{
    private TestService testService;
 
    //필드(=전역변수)에 @Autowired를 붙여봤습니다. 
    @Autowired
    private Apple apple;
    
    //생성자에 @Autowired를 붙여봤습니다.
    @Autowired
    public Test(TestService testService){
        this.testService = testService;
    }
 
    //함수에 @Autowired를 붙여봤습니다.
    @Autowired 
    public void myMethod(TestService testService){ 
        this.testService = testService; 
    }
}
cs
- 위의 예제 중 myMethod에 @Autowired를 붙인 것이 어떻게 해석되는 것인지 알아보겠습니다. Test클래스의 필드(=전역변수)인 testService에 TestService 타입 객체(≒인스턴스) myMethod메서드를 통해 자동으로 주입하도록 스프링에게 명령합니다.
 

6. @Resource = name속성을 통해 자동 주입

- 용어 정리 : 스프링에게 '딱 이 name을 가진 객체를 주입'하라고 시키는 어노테이션 

- @Resource 어노테이션은 name속성을 통해 자동 주입을 실행한다

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test{
    @Resource(name="hello")
    private Hello hello;
    private HelloService helloService;
 
    public HelloService getService(){
        return helloService;
    }
 
    @Resource(name="helloSerivce")
    public void setService(HelloService helloService){
        this.helloService = helloService;
    }
 
}
cs

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.