본문 바로가기
개발/Spring

Bean

by BellOne4222 2024. 2. 3.

Bean이란?

  • Spring IoC 컨테이너가 관리하는 자바 객체
  • Spring에서는 직접 new를 이용하여 생성한 객체가 아니라, Spring에 의하여 관리당하는 자바 객체를 사용
    • Spring에 의하여 생성되고 관리되는 자바 객체를 Bean이라고 한다.
  • Spring Framework 에서는 Spring Bean 을 얻기 위하여 ApplicationContext.getBean() 와 같은 메소드를 사용하여 Spring 에서 직접 자바 객체를 얻어서 사용

 

 

 

Spring Bean을 Spring IoC Container에 등록하는 방법

  • 자바 어노테이션(Java Annotation)을 사용하는 방법
    • Bean을 등록하기 위해서는 @Component Annotation을 사용
    • @Component Annotation이 등록되어 있는 경우에는 Spring이 Annotation을 확인하고 자체적으로 Bean 으로 등록
    • Controller 임을 Spring 에게 알려주기 위하여 @Controller Annotation을 사용
// HelloController.java
@Controller
public class HelloController {
    // Http Get method 의 /hello 경로로 요청이 들어올 때 처리할 Method를 아래와 같이 @GetMapping Annotation을 사용하여 Mapping을 사용할 수 있습니다.
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data", "This is data!!");
        return "hello";
    }
}
  • @Component Annotation 으로 인하여 Spring은 해당 Controller를 Bean 으로 등록합니다.
// Controller.java

// -- 일부 생략 --
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}



  • Bean Configuration File에 직접 Bean 등록하는 방법
    • @Configuration과 @Bean Annotation 을 이용하여 Bean을 등록할 수 있다.
    • @Configuration을 이용하면 Spring Project 에서의 Configuration 역할을 하는 Class를 지정할 수 있다.
    • 해당 File 하위에 Bean 으로 등록하고자 하는 Class에 @Bean Annotation을 사용해주면 간단하게 Bean을 등록할 수 있다.
// Hello.java
@Configuration
public class HelloConfiguration {
    @Bean
    public HelloController sampleController() {
        return new SampleController;
    }
}

 

Bean 등록 시 정보

  • Class 경로
  • Bean의 이름
    • 기본적으로는 원 Class 이름에서 첫 문자만 소문자로 변경 → accountService, userDao
    • 원하는 경우 변경 가능
  • Scope : Bean을 생성하는 규칙
    • singleton : 컨테이너에 단일로 생성
    • prototype: 작업 시마다 Bean을 새로 생성하고 싶을 경우
    • request: http 요청마다 새롭게 Bean을 생성하고 싶은 경우

'개발 > Spring' 카테고리의 다른 글

AOP(Aspect Oriented Programming)  (0) 2024.02.06
스프링 빈 이벤트 라이프 사이클  (0) 2024.02.04
IoC 컨테이너  (0) 2024.02.04
IoC(Inversion Of Controll)  (0) 2024.02.04
DI(Dependency Injection)  (0) 2024.02.04