xml이 아닌 @을 이용하여 객체를 주입하겠다.
Main.java
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx
= new AnnotationConfigApplicationContext(AppcationConfig.class);
Student student1 = ctx.getBean("student1", Student.class);
System.out.println("이름 : " + student1.getName());
System.out.println("나이 : " + student1.getAge());
System.out.println("취미 : " + student1.getHobbys());
System.out.println("신장 : " + student1.getHeight());
System.out.println("몸무게 : " + student1.getWeight());
}
}
어노테이션을 이용하여 객체를 주입받겠다고 선언함
AppcationConfig.java
@Configuration
public class AppcationConfig {
@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(70);
return student;
}
}
student1 메서드로 student 객체를 반환하여 객체를 넘겨줌
package com.example.xmljava;
import java.util.ArrayList;
public class Student {
private String name;
private String age;
private double height;
private double weight;
private ArrayList<String> hobbys;
public Student(String name, String age, ArrayList<String> hobbys) {
this.name = name;
this.age = age;
this.hobbys = hobbys;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
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;
}
public ArrayList<String> getHobbys() {
return hobbys;
}
public void setHobbys(ArrayList<String> hobby) {
this.hobbys = hobby;
}
}
'스프링' 카테고리의 다른 글
Spring bean scope (0) | 2022.10.26 |
---|---|
spring xml, @어노테이션 같이 사용한 DI (0) | 2022.10.25 |
xml을 활용한 객체 주입 (0) | 2022.10.25 |
(Spring)xml을 이용한 트랜젝션 사용 (0) | 2022.10.20 |
ResponseEntity란? (0) | 2022.10.18 |