Backend/SpringBoot

Bean 어노테이션 (W.Configuration, Component 어노테이션)

Dean83 2024. 10. 25. 14:17
  • Bean 어노테이션은 DI 를 위해 사용되는 어노테이션으로, 스프링부트 내부에 해당 어노테이션이 있는 클래스 내 함수를 등록해 두고, 사용처에서 @Autowired 등으로 인젝션 받아 사용할 수 있도록 한다. 
  • Bean 어노테이션만 사용하면 안되고, @Component 나 @Configuration 어노테이션과 같이 사용해야 한다.
  • @Component 나 @Configuration 어노테이션이 있는 클래스 내부 함수에 @Bean 어노테이션을 붙인다.
  • 요약하자면,
    • Bean으로 등록할 대상이 되는 일반 클래스 선언
    • @Component 또는 @Configuration 어노테이션이 붙은 클래스 선언
    • @Bean 어노테이션이 붙은 맴버함수 구현
      • 일반 클래스를 리턴하는 함수로 구현
    • 사용처에서 @Autowired 혹은 생성자 자동 DI 주입을 이용해 주입받고, 사용

 

  • 일반 클래스 예 (Bean으로 등록하는 대상이 됨)
package com.example.test1.test1;

public class CommonTestClass {

    public String GetStringTest()
    {
    	return "Test";
    }
}
  • Configuration, Bean 선언부 
package com.example.test1.test1;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class security {

    @Bean
    public CommonTestClass BeanTest()
    {
        CommonTestClass testClass = new CommonTestClass();
        return testClass;
    }
    
}

 

  • 호출부
package com.example.test1.test1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;


@Controller
public class javacontroller2 {

    
    private final CommonTestClass testClass;
    public javacontroller2(CommonTestClass sv)
    {
        testClass = sv;
    }

    @GetMapping("/java")
    public String controllerTest(@RequestAttribute("name") String name) {
               
        return testClass.GetStringTest();
    }
    
}