https://www.youtube.com/playlist?list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T
스프링 강의를 듣고 정리한 내용입니다
어노테이션을 이용하여 값 초기화하기
@Value 어노테이션을 이용한다
@Component
public class NewlecExam implements Exam {
@Value("20") //기본값 할당
private int kor;
@Value("30")
private int eng;
private int math;
private int com;
}
<context:component-scan>
- ApplicationContext에 등록된 빈들의 어노테이션들이 적용될 수 있게한다
- 어노테이션이 설정된 새롱운 빈들을 찾는 스캔도 할 수 있게 만든다
@Component 방식의 주의점
MVC 방식으로 웹 어플리케이션을 만드는 경우 좀 더 세분화된 어노테이션을 이용하는 것이 좋다
→ @Service, @Controller, @Repository
컴포넌트와 유사하지만, 역할에 따라 분리해서 사용할 수 있다
*참고
model과 entity는 컴포넌트를 따로 붙이지 않는다
소스코드를 가지고 있지 않은 경우 어노테이션을 붙일 수 없다
지지서 작성 방식의 변경
bean 태그를 사용하기 위해 spring을 xml과 함께 사용해야 하는가?
→ X. 어노테이션으로만 구현할 수 있게 만드는 config 설정이 존재한다
→ xml이 아닌 java 코드에 설정하는 방식을 이용한다
xml 방식
<context:component-scan base-package="spring.di.ui" />
<bean id="exam" class="spring.di.entity.NewlecExam" />
Java 코드 방식
설정을 위한 클래스 DIConfig
@Configuration 어노테이션을 붙여야 한다
@ComponentScan("spring.di.ui")
@Configuration
public class DIConfig {
@Bean
public Exam exam() { //exam()은 함수명이 아닌 컨테이너에 담긴 이름(id)에 가깝다
return new NewlecExam();
}
}
* @Bean 어노테이션 : 만든 것을 컨테이너에 담는다
ApplicationContext 생성
- AnnotationConfigApplicationContext를 이용한다
Program 클래스
ApplicationContext context = new AnnotationConfigApplicationContext(DIConfig.class);
ExamConsole console = (ExamConsole) context.getBean("console");
console.print();
또 다른 설정방법
register 함수를 이용하여 config 파일을 여러 개로 나눠서 사용할 수 있다
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
//ac.register(AConfig.class, BConfig.class);
ac.register(DIConfig.class);
ac.refresh();
ExamConsole console = (ExamConsole) context.getBean("console");
console.print();
}
'백엔드 > Spring' 카테고리의 다른 글
Spring - 어노테이션으로 객체 생성 | TIL_157 (0) | 2022.10.26 |
---|---|
Spring - @Autowired(required) | TIL_156 (0) | 2022.10.24 |
Spring - @Autowired의 참조 기준 | TIL_155 (0) | 2022.10.22 |
Spring - 어노테이션의 장점 | TIL_154 (0) | 2022.10.20 |
Spring - Collection 생성&목록 DI | TIL_153 (0) | 2022.10.17 |