단순 코드 기록/Spring

Spring_Scope

일일일코_장민기 2024. 2. 8. 11:47
728x90
main

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.dto.Student;

public class main {

public static void main(String[] args) {

ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/student.xml");
Student stu = ctx.getBean("student1", Student.class);
Student stu2 = ctx.getBean("student1", Student.class); //scope가 prototype이면 같은 아이디어도 새롭게 받아옴(주소가 달라짐)
System.out.println(stu + "\t" + stu2);
System.out.println(stu == stu2);
Student stu3 = ctx.getBean("student2", Student.class);
System.out.println(stu + "\t" + stu3);
System.out.println(stu == stu3);


}
}

 

 

Student

 

package com.dto;

public class Student {

private String username="이순신";
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String username, int age) {
super();
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}


}

 

student.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="student1" class="com.dto.Student" scope="prototype">
<!-- scope="singleton"을 하면 getBean해도 동일(default)  -->
<!-- scope="prototype"을 하면 getBean할 때마다 새로 받아옴(주소가 달라짐) -->
<property name="age" value="10"></property>
</bean>

<bean id="student2" class="com.dto.Student">
<property name="age" value="20"></property>
</bean>

</beans>

 

 

 

 

Scope가 SingleTon이면 getBean을 할 때 주소가 변하지 않음

Scope가 prototype이면 getBean을 할 때 주소가 변함

 

 

 

 

 

 

 

'단순 코드 기록 > Spring' 카테고리의 다른 글

Spring_Multi Config  (0) 2024.02.08
Spring_Autowire  (0) 2024.02.08
Spring_map  (0) 2024.02.08
Spring_list  (0) 2024.02.08
Spring_property  (0) 2024.02.08