스프링
[Spring] @Component를 이용한 객체 생성 방법
Awdsd
2020. 4. 8. 15:56
반응형
이번 포스팅에서는 기존의 XML에 bean(객체를)을 생성했던 방식에서 직접 JAVA 코드에서 객체를 생성하는 방법에 대해 알아보자.
1. @Component
먼저 기존의 XML을 통해 bean을 만들던 것을 보자.
<bean id="console" class="spring.di.ui.InlineExamConsole" />
위의 코드처럼 <bean>태그를 사용해서 객체를 생성했다. 이것을 @Component Annotation을 이용해서 아래와 같이 할 수 있다.
@Component("console") //"console"은 bean의 id
public class InlineExamConsole implements ExamConsole {
@Autowired
private Exam exam;
public InlineExamConsole() {
}
public InlineExamConsole(Exam exam) {
this.exam = exam;
}
//후략..
}
@Component의 의미는 클래스를 bean으로 등록한다라는 의미이다.
주의할 점은 @Component를 선언하고 이것을 xml에서 읽게 하기 위해서는 XML에 아래와 같은 태그를 달아줘야한다.
<!-- @Component가 있는 클래스의 Package를 스캔하라는 뜻 --!>
<!-- @Component가 있는 클래스가 여러 패키지에 있을 경우 ,를 통해 여러개 입력 --!>
<context:component-scan base-package="spring.di.ui, spring.di.entity" />
2. @Value
그렇다면 @Component를 이용해서 객체를 만들었는데 안의 property는 어떻게 설정할까? 기존에는 아래처럼 <constructor-arg>, <property>를 이용해 변수에 값을 설정해줬다. 이것을 @Component를 이용해 만든 객체에서는 @Value를 이용해 값을 설정할 수 있다.
<bean id="exam" class="spring.di.entity.NewlecExam">
<constructor-arg name="kor" value="30"/>
<constructor-arg name="eng" value="20"/>
<constructor-arg name="com" value="10"/>
<constructor-arg name="math" value="0"/>
</bean>
@Component("exam")
public class NewlecExam implements Exam {
@Value("20")
private int kor;
@Value("40")
private int eng;
private int math;
private int com;
//후략..
}
각 변수에 @Value Annotation을 사용해 값을 설정한다. NewlecExam도 bean으로 생성하기 때문에 @Component를 사용한다.
참고
https://www.youtube.com/watch?v=pyMzPpK4uXk&list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T&index=16
반응형