Spring Boot Application Overview (1)
Spring 이란 Java 기반 애플리케이션 개발을 도와주는 오픈소스 프레임워크이다.
쉽게 말하면, Instruction이 있는 라이브러리 모음집이 아닐까 생각한다.
Spring의 특성과 원리
SpringApplication이 실행되면 ApplicationContext(Spring Container) 객체가 생성된다.
Application Context는 Configuration MetaData(Annotation, Xml, Java기반)을 읽어서 POJO(Business Objects, 순수자바객체)에 객체를 생성하고 의존성을 주입한다.
Application Context는 Bean(객체)아이디와 객체 주소를 Map형태로 가지고 있다가 객체가 필요할때 객체를 꺼내준다.
객체는 한번 생성하면 나중에 다시 호출할 때 새로 생성하지 않고 이미 생성된 객체를 계속해서 재활용한다.
이를 싱글톤(Singleton)패턴이라 한다.
물론 Annotation으로 Prototype으로 설정하여 매번 새로 생성하게 할 수도 있다.
//Spring Container 초기화 시작 [ApplicationContext객체생성 시작]
ApplicationContext applicationContext = SpringApplication.run(SpringBootBeanCreateApplicationMain.class, args);
//스프링 컨테이너(application context)에 등록된 빈의 아이디로 스프링 빈 객체의 참조 얻기
ProductDao productDao =(ProductDao) applicationContext.getBean("productDao");//설정한 이름
UserService userService =(UserService) applicationContext.getBean("userServiceImpl");//설정하지 않은 경우 클래스이름 첫글자 소문자
//스프링 컨테이너(application context)에 등록된 빈의 클래스로 스프링 빈 객체의 참조 얻기
ProductDao productDao2 =(ProductDao) applicationContext.getBean(ProductDao.class);//인터페이스를 구현한 모든 클래스
ProductService productService2 =(ProductService) applicationContext.getBean(ProductService.class);//인터페이스를 구현한 모든 클래스
System.out.println("-----빈의 scope[singleton]------");
System.out.println(applicationContext.getBean(ProductDao.class));//모두 동일 객체
System.out.println(applicationContext.getBean(ProductDao.class));//모두 동일 객체
System.out.println(applicationContext.getBean("productService"));//모두 동일 객체
System.out.println("-----빈의 scope[singleton]------");
@Repository
public class GuestDaoImplMyBatis implements GuestDao{
@Autowired(required=true)
private GuestMapper guestMapper;
GuestDaoImplMyBatis객체는 GuestMapper를 필드를 필수로 갖는데
@Autowired(required=true) 어노테이션으로 자동으로 주입된다.
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().type(DriverManagerDataSource.class).build();
}
}