주뇽's 저장소
[Java Spring ] Spring Bean을 이용하여 객체 관리 본문
728x90
반응형
Spring Bean이란, Spring 프레임워크에서 관리하는 객체이며 여기서 말하는 관리란 객체의 생성, 생명주기, 그리고 그 객체에 대한 요청들을 처리한다는 의미이다.
1. Launch a Spring Context
var context = new AnnotationConfigApplicationConext(2번에서 미리설정한configuration.class);
2. 원하는이름Configuration.java 파일 생성 후 @Configuration 어노테이션을 이용하여 Bean 생성
@Bean
public String name(){
return "HONG";
}
3. context.getBean("name") 을 통해 전역변수로 설정된 Bean을 확인 할 수 있다!
스프링이 관리하고자 하는 객체들을 미리 설정
package com.gaming.gamingapp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record Person (String name, int age){};
// 레코드를 이용하며 생성자, getter, setter 노 필요
record Address (String first, String city){};
@Configuration
public class ExampleConfig {
@Bean
public String name(){
return "HONG";
}
@Bean
public int age(){
return 15;
}
@Bean
public Person person(){
return new Person("PARK", 25);
}
@Bean
public Person personUseBeanWithMethod(){
return new Person(name(), age());
// 기존의 Bean인 name과 age를 이용하여 새로운 Bean을 생성 가능
}
@Bean
public Person personUseBeanWithParameters(String name, int age){
return new Person(name, age);
}
@Bean
public Address address(){
return new Address("성북구", "서울특별시");
}
}
다른 클래스에서 해당 객체들을 호출
package com.gaming.gamingapp;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppConfigBasic {
public static void main(String [] args){
// 1번 Config 연결
var context =
new AnnotationConfigApplicationContext(ExampleConfig.class);
// 2 번 Config 파일 생성 후 원하는 설정 적
// 3번 확인
System.out.println(context.getBean("name"));
System.out.println(context.getBean("age"));
System.out.println(context.getBean("person"));
System.out.println(context.getBean("personUseBeanWithMethod"));
System.out.println(context.getBean("personUseBeanWithParameters"));
System.out.println(context.getBean(Address.class));
}
}
즉 Bean을 이용하면 Spring 프레임워크가 객체를 직접 관리해준다.
- Spring은 각 Bean을 싱글턴으로 관리하여, 요청마다 새로운 객체를 만들지 않고 동일한 객체를 재사용한다.
- 의존성 주입: Bean들 사이의 의존성은 Spring이 자동으로 처리하여, 개발자는 의존 객체를 직접 만들 필요가 없다.
- 기존의 Bean을 이용하여 새로운 Bean을 설정할 수 있다.
- 메서드를 이용
- 파라미터를 이용
Bean Scope
@Scope(value =. onfigurableBeanFactory.SCOPE_PROTOTYPE)
어노테이션을 사용하면 싱글톤이 아닌 매번 다른 인스턴스를 생성할 수 있다.
'웹개발 > SpringBoot' 카테고리의 다른 글
[Java Spring] JDBC, Spring JDBC, JPA, Spring JPA (2) | 2023.11.24 |
---|---|
[Java Spring] Spring FrameWork (0) | 2023.11.22 |
[Java Spring] 의존성 주입 방법 (0) | 2023.11.21 |