공부기록/Spring

Spring - Bean

jhs0129 2021. 12. 24. 17:24
320x100
반응형

spring공부함에 있어서 내용은 인프런 김영한님 강의를 듣고 정리한 것입니다 (필기 및 공부정리용)

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8#

 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., 스프링 핵심 원리를 이해하고, 성장하는 개발자가 되어보세요! 📢 수강 전

www.inflearn.com

 

빈 라이프사이클

스프링 컨테이너는 빈 객체를 생성, 초기화, 소멸할 때 의 라이프 사이클

스프링 컨테이너 생성 -> 스프링 빈 생성 -> 의존관계 주입 //여기까지 객체 생성, 프로퍼티 설정

-> 초기화 콜백 -> 사용 -> 소멸전 콜백 -> 스프링 종료

초기화 소멸방법

  • 인터페이스
  • 어노테이션
  • 설정정보에 메서드 지정

인터페이스 사용

//초기화 콜백
public interface InitializingBean{
    void afterPropertiesSet() throws Exception;
}

//소멸 전 콜백
public interface DisposableBean{
    void destory() throws Exception;
}
@Component
public class MemberServiceImpl 
implements MemberService, InitializingBean, DisposableBean {

    private final MemberRepository memberRepository;
    ...
    @Override 
    public void afterPropertiesSet() throws Exception {
        System.out.println("MemberServiceImpl Start");        
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("MemberServiceImpl Finish");
    }
}

public class MemberApp {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = 
        new AnnotationConfigApplicationContext(AppConfig.class);

        MemberService memberService = ac.getBean(MemberService.class);

        Member member = new Member(1L, "memberA", Grade.VIP);
        memberService.join(member);

        System.out.println("new member: " + member.getName());

        ac.close();
    }
}

설정정보에 메서드 지정

메서드는 위와 동일하게 bean객체 내부에 작성 후 해당 메서드 이름을 설정파일에 적용 해주면 된다

java 적용 방법

@Configuration
public class AppConfig {

    @Bean(initMethod = "init", destroyMethod = "close")
    public MemberService memberService() {
        return new MemberServiceImpl(memberRepository());
    }
}

xml 적용 방법

<bean id="memberService" class="com.jhs.Member.MemberServiceImpl"
    init-method="init" destroy-method="close">
    <constructor-arg name="memberRepository" ref="memberRepository"/>
</bean>

어노테이션★

  • 스프링에 종속적인 기능이 아니라 자바 표준이다
  • 외부 라이브러리를 초기화 소멸에 적용 못한다
  • 그때는 설정정보에 메서드 지정해서 사용하면 된다
@Component
public class MemberServiceImpl implements MemberService {

    private final MemberRepository memberRepository;
    ...
    @PostConstruct //초기화 시 호출
    public void init() throws Exception {
        System.out.println("MemberServiceImpl Start");        
    }

    @PreDestroy //소멸 시 호출
    public void close() throws Exception {
        System.out.println("MemberServiceImpl Finish");
    }
}

빈 스코프

빈이 존재할 수 있는 범위

싱글톤

기본 스코프, 스프링 컨테이너의 시작부터 종료까지 유지되는 범위

설정파일에서 @Scope("singleton")지정, 지정하지 않아도 default값으로 설정된다

프로토타입

생성과 의존관계 주입만 관여후 컨테이너에서 삭제됨

getBean을 통해서 빈을 호출 하면 매번 호출 시 새로 빈을 생성하기 때문에 다 다른 객체가 호출 된다

설정파일에서 @Scope("prototype")지정

싱글톤과 프로토타입을 같이 사용 하는 경우

싱글톤 내부에 사용자가 각자의 프로토타입 객체를 원할 경우에 싱글통 객체를 호출 하면 내부 프로토타입 객체는 동일 한 객체이다

싱글톤 빈이 생성과 의존성 주입 후 계속 프로토타입 객체와 유지 되기 때문이다

싱글톤 빈이 각각의 프로토타입빈을 가지도록 하는 법

  1. 싱글톤 빈이 프로토타입 빈을 사용 할때마다 새로 생성
  2. ObjectProvider사용 - 스프링에 의존
    static class ClientBean {
    @Autowired private ObjectProvider<PrototypeBean> prototypeBeanProvider; 
    public int logic() { 
        PrototypeBean prototypeBean = prototypeBeanProvider.getObject(); 
        prototypeBean.addCount(); 
        int count = prototypeBean.getCount(); 
        return count; 
    } 
    } 
    @Scope("prototype") 
    static class PrototypeBean { 
    private int count = 0; 
    public void addCount() { count++; } 
    public int getCount() { return count; } 
    @PostConstruct 
    public void init() { 
        System.out.println("PrototypeBean.init " + this); 
    } 
    @PreDestroy 
    public void destroy() {
        System.out.println("PrototypeBean.destroy"); 
    } 
    }
  3. JSR-330 Provider사용 - java표준
    @Autowired 
    private Provider<PrototypeBean> provider; 
    public int logic() {
    PrototypeBean prototypeBean = provider.get(); 
    prototypeBean.addCount(); 
    int count = prototypeBean.getCount(); 
    return count; 
    }

롬복

  • 어노테이션 기반의 코드 자동 생성
  • 반복되는 코드 작성 불필요
  1. dependency 추가
  2. <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency>
  3. lombok.jar 다운로드
  4. projectlombok.org/download
  5. specify location에서 eclipse.exe경로를 찾고 install

annotation 종류

  • @Data
  • @AllArgsConstructor
  • @NoArgsConstructor
  • @RequiredArgConstructor
  • @Getter
  • @Setter
  • @EqualsAndHashCode
  • @ToString
  • @Builder

 

spring공부함에 있어서 내용은 인프런 김영한님 강의를 듣고 정리한 것입니다 (필기 및 공부정리용)

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8#

 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., 스프링 핵심 원리를 이해하고, 성장하는 개발자가 되어보세요! 📢 수강 전

www.inflearn.com

 

320x100
반응형