Spring 어노테이션, 컨트롤러 개념
Spring 어노테이션, 컨트롤러 개념
Spring - @Autowired
@Autowired
는 필요한 의존 객체를 스프링이 자동으로 주입해준다.
1
2
@Autowired
private Chef chef;
Spring - @Component
@Component
는 해당 클래스를 스프링이 관리하는 Bean으로 등록한다.
1
2
3
4
5
6
7
8
9
@Component
public class SampleHotel {
private final Chef chef;
@Autowired
public SampleHotel(Chef chef) {
this.chef = chef;
}
}
이 어노테이션을 사용하려면 root-context.xml
에 Bean 스캔을 설정해야 한다.
1
<context:component-scan base-package="패키지명"></context:component-scan>
그리고 root-context.xml
의 아래쪽 NameSpaces 탭에서 context
항목을 체크해야 한다.
Spring - 세팅 방법
프로젝트 생성
- Spring Legacy Project (Spring MVC Project)
서버 포트번호 설정
- Servers 탭 > Tomcat 설정 더블클릭
- Overview 탭에서 포트번호 변경
- Modules 탭에서 Path를
/
로 수정
pom.xml 설정 변경
- Java 버전:
1.6
→11
- Spring 버전:
3.1.1.RELEASE
→5.0.7.RELEASE
- JUnit 버전:
1 2 3 4 5 6
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
- Log4j 버전:
1 2 3 4 5
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- Maven Compiler Plugin:
1 2 3 4 5 6 7 8 9 10 11 12
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>11</source> <target>11</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin>
- Java 버전:
Spring - Controller 사용하기
컨트롤러는 서블릿을 대신해 요청을 처리하는 역할을 한다. 어노테이션:
@Controller
: 해당 클래스를 컨트롤러로 지정@RequestMapping
: 요청 URL을 매핑
1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping("/ex01")
public String ex01(SampleDTO dto) {
log.info("" + dto);
return "ex01";
}
@RequestMapping("/ex02")
public String ex02(@RequestParam("str") String name, @RequestParam("num") int age) {
log.info("name : " + name);
log.info("age :" + age);
return "ex02";
}
SampleDTO
와 같은 객체를 파라미터로 설정하면, 자동으로 바인딩되어 뷰 페이지로 전달된다.
뷰에서는 다음처럼 사용 가능:
1
2
3
<body>
${sampleDTO.name}
</body>
여러 파라미터를 배열, 리스트로 받기
같은 이름으로 여러 값이 넘어올 경우 배열이나 리스트로 받을 수 있다.
1
2
3
4
5
6
7
8
9
10
11
@RequestMapping("/ex02List")
public String ex02List(@RequestParam("ids") ArrayList<String> ids) {
log.info("ids : " + ids);
return "ex02List";
}
@RequestMapping("/ex02Array")
public String ex02Array(@RequestParam("ids") String[] ids) {
log.info("ids : " + Arrays.toString(ids));
return "ex02List";
}
This post is licensed under CC BY 4.0 by the author.