티스토리 뷰
DI Annotation예제
- 이클립스 사용
- xml파일 대신 자바로ㅇㅇ
- 강사는 그닥 추천하는 방법은 아니라고 한다
<Student>
- package com.javalec.ex;
- import java.util.ArrayList;
- public class Student {
- private String name;
- private int age;
- private ArrayList<String> hobbys;
- private double height;
- private double weight;
- this.name = name;
- this.age = age;
- this.hobbys = hobbys;
- }
- return name;
- }
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public ArrayList<String> getHobbys() {
- return hobbys;
- }
- public void setHobbys(ArrayList<String> hobbys) {
- this.hobbys = hobbys;
- }
- public double getHeight() {
- return height;
- }
- public void setHeight(double height) {
- this.height = height;
- }
- public double getWeight() {
- return weight;
- }
- public void setWeight(double weight) {
- this.weight = weight;
- }
- }
-> name, age, hobby는 생성자랑 getter,setter 다 만듬
<ApplicationConfig> - xml파일 역할을 하는 클래스
- package com.javalec.ex;
- import java.util.ArrayList;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- @Configuration // ApplicationConfig가 스프링 파일로 사용될 클래스임을 명시
- public class ApplicationConfig {
- @Bean //Bean 설정
- public Student student1() {
- ArrayList<String> hobbys = new ArrayList<String>();
- hobbys.add("테니스");
- hobbys.add("영화보기");
- Student student = new Student("홍길동", 20, hobbys);
- student.setHeight(180);
- student.setWeight(80);
- return student;
- }
- @Bean //Bean 설정
- public Student student2() {
- ArrayList<String> hobbys = new ArrayList<String>();
- hobbys.add("독서");
- hobbys.add("음악감상");
- Student student = new Student("홍길자", 21, hobbys);
- student.setHeight(165);
- student.setWeight(47);
- return student;
- }
- }
->
<MainClass>
- package com.javalec.ex;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- public class Mainclass {
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
- Student student1 = ctx.getBean("student1", Student.class);
- Student student2 = ctx.getBean("student2", Student.class);
- ctx.close();
- }
- }
<결과>
'Spring' 카테고리의 다른 글
Spring 2 (0) | 2020.10.13 |
---|---|
Spring 1 (0) | 2020.10.13 |
[Spring] DI 기본예제 3 (0) | 2018.05.13 |
[Spring] DI 기본예제 2 (0) | 2018.05.13 |
[Spring] DI 기본예제 (0) | 2018.05.13 |
댓글
최근에 올라온 글
최근에 달린 댓글
링크
- Total
- Today
- Yesterday