⭐Bean 이란 ?
spring 컨테이너가 관리하는 객체이가 바로 빈이다. new 연산자로 생성하는 자바 객체는 스프링이 관리하지 않기 떄문에 빈이 아니다
⭐스프링 컨테이너
Bean의 저장소, Bean을 저장,관리(생성,소멸,연결)을 스프링 컨테이너가 해준다.
⭐Bean 등록방법
빈을 등록하는 방법은 3가지
- xml 파일에 직접 등록
- @Bean 어노테이션을 이용
- @Component, @Controller, @Service, @Repository 어노테이션을 이용
1. 객체를 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="car" class="com.fastcampus.ch3.Car"/>
<bean id="turboEngine" class="com.fastcampus.ch3.TurboEngine"/>
</beans>
2.@Bean 어노테이션을 이용
package com.example.myapp.di;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
@Configurable
@ComponentScan(basePackages= {"com.example.myapp"})
@ImportResource(value= {"classpath:application-config.xml"})
public class AppConfig {
@Bean
public IHelloService helloService() {
return new HelloService();
}
@Bean
public HelloController helloController() {
HelloController controller = new HelloController();
controller.setHelloService(helloService());
return controller;
}
}
메서드 위에 @Bean태그를 사용하고 AppConfig 객체 위에 @Configurable, @ComponentScan, @ImportResource 어노테이션을 선언해준다.
3.Componet scan
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.fastcampus.ch3">
<context:exclude-filter type="regex" expression="com.fastcampus.ch3.diCopy*.*"/>
</context:component-scan>
<context:annotation-config/>
</beans>
servelt-context.xml에 파일에 스캔대상 패키지를 정해주면 하위 패키지 까지 뒤져서
클래스에 @ componet 어노테이션이 붙어있으면 빈 으로 등록해준다
(@controller @service @repository) 는 componet를 포함하고있기떄문에 이 것도 빈으로 등록해준다.
⭐Bean은 기본적으로 싱글톤이다 .
호출할떄마다 새로운 객체가 만들어지개 하려면 scopec에 prototype을 선언 하면됌, singleton이 기본값.
<bean id="car" class="com.fastcampus.ch3.Car" scope="prototype"/>
'Develop > Spring' 카테고리의 다른 글
[Spring] @Autowired @Resource @Qualifire 차이 (0) | 2024.08.29 |
---|---|
[Spring] IoC/Di? 객체 주입 방법 (0) | 2024.08.29 |
[Spring] Spring vs Springboot 차이 (0) | 2024.06.02 |
[Spring] 스프링 xml 설정 파일 - web.xml, root-context.xml, servlet-context.xml 차이 (0) | 2024.05.21 |
[Spring] DAO,DTO,VO 알아보기 (0) | 2024.03.13 |