스프링 빈(Spring Bean)은 스프링 IoC 컨테이너에 의해 생성되고 관리되는 객체입니다.
IoC 컨테이너 안에 들어있는 객체로 필요할 때 IoC컨테이너에서 가져와서 사용합니다. 애너테이션을 사용하거나 xml설정을 통해 일반 객체를 Bean으로 등록할 수 있습니다.
Spring Container 에 의해 생명주기가 관리된다.
@controller, @service, @Repository , @ Component 붙은 클래스들 빈으로 생성
@Configuration붙은 클래스에서 Bean 등록
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
<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="myService" class="com.example.MyService"/>
<bean id="myRepository" class="com.example.MyRepository"/>
</beans>
아래와 같이 xml파일에서 폴더에 componentscan 걸어준다.
<context:component-scan base-package="com.example" />
++) springboot 에서는 @SpringBootApplication 가 자동으로 해줌
@Autowired 애너테이션을 붙여줌으로써 주입 가능하다.
초기화는 주로 외부 리소스 연결시 사용되는데 예를들면 DB연결, 파일 처리, 네트워크 소켓 , 스레드 풀 과 같은 자원을 사용할 때 초기화와 정리작업이 필요할 수 있다.
--> 위 예시 모두 연동 프로그램이 없으면 직접 초기화 해줘야 되지만 DB연결은 JDBC, 커넥트 풀이 Servlet이 스레드 풀과 같은 자원을 이용하는 것은 Tomcat 프로그램이 자동으로 커버해줌으로써 대부분 자동으로 된다.
이것이 내가 웹 개발할 때 초기화를 쓴 기억이 없는 경우
사용은 웹 개발을 할때는 위와 같이 생성,의존성주입으로 짠 코드가 spring에 의해 실행되어 bean이 사용된다.
앱이 종료되면 자동으로 소멸된다.