티스토리 뷰

서버/Spring

[Spring] 스프링 빈(Bean)

sm.jeon 2024. 2. 4. 23:02
반응형

스프링 빈?

스프링 IoC(Inversion Of Control) 컨테이너에 의해 관리되는 재사용 가능한 소프트웨어 컴포넌트. 이곳에서 관리하는 인스턴스를 Bean이라고 한다.

 

의존성 주입 (DI, Dependency Injection)을 위해 사용한다.

 

스프링 빈 등록 방법

빈을 등록할 때, 기본적으로 싱글톤으로 등록된다. 

xml에 등록(잘 사용하지 않음)

<bean id="exampleService" class="com.example.ExampleService"/>

<bean id="exampleController" class="com.example.ExampleController" p:exampleService-ref="exampleService"/>

 

@Bean 어노테이션 사용

@Configuration
class BeanInstance {
    @Bean
    fun exampleService() = ExampleService()
    
    @Bean
    fun exampleController(service: ExampleService) = ExampleController(service)
}

 

@Component, @Controller, @Service, @Repository 어노테이션 사용

@Component
class ExComponent

@RestController // @Controller도 가능
class ExController

@Service
class ExService

@Repository
class ExRepository

 

등록한 빈 주입하기

@Autowired 어노테이션을 사용해 생성자를 통해 의존성을 주입할 수 있다.

@RestController
class ExController @Autowired constructor(
	private val service: ExService
)

@RestController
class ExController {
	@Autowired
	lateinit var service: ExService
}
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함