추상화 POJO 클래스를 빈으로 등록하기
이 글 애서는 Person이라는 추상화 클래스를 만들고 빈으로 등록할 것이다. 하지만 실제 빈으로 등록되는 구현체는 Person 클래스를 상속받은 Student와 Business가 된다.
먼저 Person 추상화 클래스를 만들자.
@Data
@NoArgsConstructor
@AllArgsConstructor
public abstract class Person {
private String name;
private int age;
}
그리고 Student 클래스와 Business 클래스를 만들자.
@Setter
public class Student extends Person{
private String schoolName;
private int studentNumber;
public Student(){ super(); }
public Student(String name, int age) {
super(name, age);
}
public String toString() {
return super.toString() + " And School Name : " + this.schoolName;
}
}
public class Business extends Person {
@Setter
private String companyName;
public Business() { super(); }
public Business(String name, int age) { super(name, age); }
public String toString() { return super.toString() + " And CompanyName : " + this.companyName; }
}
다음으로 Person 객체를 스프링 IoC 컨테이너에 빈으로 등록하기 위해 Configuration 컴포넌트를 만든다.
@Configuration
public class PersonConfiguration {
@Bean
public Person student() {
Student student = new Student("kevin",17);
student.setSchoolName("jeju international high school");
student.setStudentNumber(2019224774);
return student;
}
@Bean
public Person business() {
Business business = new Business("marry", 33);
business.setCompanyName("bitnine");
return business;
}
}
마지막으로 스프링 IoC 컨테이너에서 Person 빈 객체(Student와 Business)를 꺼내와서 확인해보자.
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfiguration.class);
Person student = context.getBean("student", Person.class);
Person business = context.getBean("business", Person.class);
System.out.println(student); //Person(name=kevin, age=17) And School Name : jeju international high school
System.out.println(business); //Person(name=marry, age=33) And CompanyName : bitnine
}
}
참고도서
제목: 스프링5레시피(4판)
지은이: 마틴데니엄, 다니엘 루비오, 조시 롱
옮긴이: 이일웅
펴낸곳: 한빛미디어