Spring
자바 기반의 엔터프라이즈 급 어플리케이션을 만들 수 있는 Framwork
JEE가 제공하는 다양한 기능을 제공하는 것 뿐만 아니라, DI나 AOP같은 기능도 지원
개발자가 복잡하고 실수하기 쉬운 Low Level에 신경 쓰지 않고, Business Logic 개발에 전념할 수 있도록 해줌
프레임워크와 라이브러리의 차이점 "제어 흐름이 어디에 있는가" 프레임워크 는 전체적인 흐름을 쥐고 있으며 애플리케이션의 코드는 프레임워크에 의해 사용됨 (프레임워크 )라이브러리 는 개발자가 전체적인 흐름을 만들며 라이브러리를 가져다 씀 (개발자 )
IoC (Inversion of Control, 제어의 역전)
객체지향 언어에서 Object 간의 연결 관계를 런타임 에 결정
객체 간의 관계가 느슨하게 연결됨 (loose coupling )
IoC의 구현 방법 중 하나가 DI (Dependency Injection)
객체간 결합도가 높으면?!?! 해당 클래스가 유지보수 될 때 그 클래스와 결합된 다른 클래스도 같이 유지보수 되어야 할 가능성이 높음
DI (Dependency Injection, 의존성 주입)
객체 간의 의존관계를 자신이 아닌 외부의 조립기가 수행
인터페이스를 사이에 두어 클래스 레벨에서는 의존관계가 고정되지 않고, 런타임 시에 동적으로 주입
high cohesion loose coupling (유연성 확보, 결합도 낮춤)
Setter Injection, Constructor Injection, Field Injection
Spring에서는 Constructor Injection 권장 * 생성자가 1개만 있는 경우 @Autowired 생략 가능 * 동일한 타입의 bean이 여러개일 경우에는 @Qualifier("name") 으로 식별
Spring DI 용어 정리Bean (빈)
스프링이 IoC 방식으로 관리하는 오브젝트
스프링이 직접 그 생성과 제어를 담당하는 오브젝트만을 Bean이라고 부름
스프링 빈은 기본적으로 싱글톤으로 생성 (생성 범위 : singleton, prototype, request, session)
BeanFactory (빈팩토리)
스프링 IoC를 담당하는 핵심 컨테이너 (빈의 라이프 사이클 관리)
Bean을 등록, 생성, 조회, 반환하는 기능을 담당
ApplicationContext
BeanFactory를 확장한 IoC 컨테이너
스프링이 제공하는 각종 부가 서비스를 추가로 제공
configuration metadata : BeanFactory가 IoC를 적용하기 위해 사용하는 메타정보
Spring Bean 설정
XML
XML 문서 형태로 빈의 설정 메타 정보를 기술
단순하며 사용하기 쉬움
<bean> 태그를 통해 세밀한 제어 가능
<!-- applicationContext.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"
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-4.3.xsd">
<bean id="memberDao" class="com.test.hello.dao.MemberDaoImpl" />
<bean id="memberservice" class= "com.test.hello.service2.MemberserviceImpl" scope="prototype">
<property name= "memberDao" ref="memberDao"/>
<bean id="adminService" class="com.test.hello.service.AdminServiceImpl"/>
</beans>
기본 속성 name : 주입 받을 곳에서 호출 할 이름 설정 id : 주입 받을 곳에서 호출 할 이름 설정 (유일값) class : 주입 할 객체의 클래스 factory-method : Singleton 패턴으로 작성된 객체의 factory 메소드 호출
Annotation
어플리케이션의 규모가 커지고 빈의 개수가 많아질 경우 XML 파일을 관리하는 것이 번거로움
빈으로 사용될 클래스에 특별한 annotation을 부여해주면 자동으로 빈 등록 가능
“오브젝트 빈 스캐너”로 “빈 스캐닝”을 통해 자동 등록
빈스캐너는 기본적으로 클래스 이름을 빈의 아이디로 사용
정확히는 클래스 이름의 첫글자만 소문자로 바꾼 것을 사용
Annotation으로 빈을 설정하는 경우 반드시 component-scan 을 설정해야함
<!-- applicationContext.xml -->
<context: component-scan base-package="com.test.hello.*"/>
@Component
public class MemberServiceImpl implements Memberservice {
@Autowired
private MemberDao memberDao;
@Override
public int registerMember (MemberDto memberDto) {
return memberDao.regist(memberDto);
}
}
Stereotype Annotation
빈 자동등록에 사용할 수 있는 annotation
계층별로 빈의 특성이나 종류를 구분
AOP Pointcut 표현식을 사용하면 특정 annotation이 달린 클래스만 설정 가능
특정 계층의 빈에 부가기능을 부여 가능
@Repository : DAO 또는 Repository 클래스에 사용@Service : Service Layer 클래스에 사용@Controller : Presentation Layer의 MVC Controller에 사용@Component : 위의 Layer 구분을 적용하기 어려운 일반적인 경우에 설정
Bean 객체 얻기
ApplicationContext ctx = new GenericXmlApplicationContext("file:resources/applicationContext.xml");
CommonService memberService = ctx.getBean(MemberService.class);
CommonService adminService = ctx.getBean(AdminService.class);