Spring 개념

밍키·2023년 12월 15일
0

Spring Framework

목록 보기
2/5
post-thumbnail

FrameWork란?

어플리케이션을 개발하기 위해 기본 뼈대가 제공
개발자는 주어진 뼈대에 (business logic)을 붙이는 작업만 수행

  • 장점
  1. 빠른 구현시간
  2. 유지보수가 용이
  3. 초급 개발자도 프레임 워크를 통해 세련되고 효율적인 코드를 생산
  4. 검증된 architecture의 재사용과 일관성 유지

Spring Framework

  • IOC와 AOP를 지원하는 경량의 프레임워크이다
  1. 경량의 프레임워크 이다
  2. 제어의 역행 : 객체 생성및 객체간 의존관계를 컨테이너가 처리
  3. AOP(관점지향 프로그래밍) : 여러메소드에 공통으로 사용되는 cross-cutting-concern을 독립된 클래스로 분리하고 해당 기능을 선언적으로 처리하여 적용

DI (Dependency Injection) : 의존주입

아래 예제에서 스프링 컨테이너는 AccountDao를 Bean 객체로 설정하고 각 클래스마다 해당 객체가 필요할 시점에 할당(주입)을 해준다 , 주입을 해주는 방식은 xml방식과 java클래스 방식이 있고 dao객체가 생성되는 방식은 생성자 방식과 Setter 방식이있다

	<bean id = "dao" class = "bank.AccountDAO"></bean>

    <bean id = "cservice" class = "bank.AccountCreateService">
        <constructor-arg ref = "dao"></constructor-arg>
    </bean>

    <bean id = "tservice" class = "bank.TransactionService">
        <constructor-arg ref = "dao"></constructor-arg>
    </bean>

우선 dao라는 id를 가진 bean 객체를 생성해주고 class 부분에는 bank라는 패킥지안에 AccountDAO 클래스를 통해 생성을 한 모습이다

다음 아래를 보면 cservice와 tservice라는 이름을 가진 bean 객체가 dao를

생성자 방식으로 생성

할때 constructor-arg 태그를 이용하여 ref안에 bean 객체를 넣어서 생성한다

위 방식이 xml 방식이다

Setter 방식으로 사용하는경우

xml 코드

<bean id = "tv2" class = "di.ex02.LgTV">
  <property name = "speaker" ref = "apple"/>
  <property name = "model" value = "75인치"/>
</bean>

propery 태그를 이용하여 Setter방식으로 설정한다

//xml파일을 설정 정보로 사용할경우 GenericXmlApplicationContext 클래스 필요
ApplicationContext ctx = new GenericXmlApplicationContext("classpath:config.xml");

java 클래스 방식으로 bean 설정

	 @Bean
    public AccountDAO dao()
    {
        return new AccountDAO();
    }

    @Bean
    public BasicReport basicReport()
    {
        return new BasicReport();
    }
//
//    @Bean
//    public summeryReport sReport()
//    {
//        return new summeryReport();
//    }
//
    @Bean(name = "cservice")
    public AccountCreateService accountCreateService()
    {
        return new AccountCreateService(dao());
    }
//
    @Bean (name = "tservice")
    public TransactionService transactionService()
    {
        return new TransactionService(dao());
    }

    @Bean (name = "one")
    public ReportOneAccountService reportOneAccountService()
    {
        ReportOneAccountService oneAccountService = new ReportOneAccountService();
        oneAccountService.setDao(dao());
        oneAccountService.setPrinter(basicReport());
        return oneAccountService;
    }

    @Bean(name = "every")
    public ReportEveryAccountService reportEveryAccountService()
    {
        ReportEveryAccountService oneAccountService = new ReportEveryAccountService();
        oneAccountService.setDao(dao());
        oneAccountService.setPrinter(basicReport());
        return oneAccountService;
    }

자바 코드 방식으로 bean 객체를 만드는 방법이고 이 방법을 쓰려면 본 클래스에 @Configuration 어노테이션이 필요하다 이는 클래스를 Bean 설정으로 사용한다는 의미이다

자바를 이용할경우 ApplicationContext는 아래와 같다

ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

XML vs JAVA annotation 비교

  • XML 설정
  1. Bean 설정을 변경할때는 XML만 변경하면된다
  2. 모든 Bean의 정보가 XML파일에만 있음 유지보수하기 용이?
    but 대용량의 XML 파일이 여러개가 있다면? 안좋을 수도..
  3. IDE 기능에따라 XML 작성과정이 다소 번거롭다
  4. 프로그램을 실행하기 전까지는 오류를 확인하기 어려움
  • JAVA annotation 설정
  1. 컴파일러의 도움으로 오타와 설정정보 오류를 미리 알수있다
  2. IDE가 코드 자동완성 기능의 도움을 받을수있다
  3. 설정정보변겨이 코드를 다시 컴파일해야한다

XML 설정과 JAVA annotation을 함께 사용

  1. XMl 설정에서 java 사용
<context:annotation-config/> 태그를 입력한다
  • @Configurarion 태그가 적용된 클래스를 태그를 사용해 Spring bean으로 등록한다
  1. java에서 XML 사용
  • @Configuration 파일에 @ImportResource(xml 파일이름) annotation을 추가

의존 자동 설정 @Autowired

@Autowired 어노 테이션은 bean객체중에 타입이 하나만있을때 자동으로 연결을 해주는 것으로 코드가 간결해진다 @Autowired 어노테이션은 생성자와 필드 메서드 총 세 곳에 적용가능하다

@Qualifier : 같은 타입의 객체가 여러개가 있을경우 연결할 객체를 한정할 때 사용

@Resource : 위 두개의 어노테이션을 합친것 이름을 기준으로 선택 @Autowired는 타입을 기준으로 선택

@Inject : @Autowired 와 같은 의미

XML을 통한 DI 설정시 <context:annotation-config/> 내용이 포함 되어 있어야 한다

Component Scan을 이용한 Bean 자동등록

  • 특정 패키지에 위치한 클래스들을 자동으로 bean 객체로 등록하는 기능
  • XML : <context:component-scan base-package="패키지이름"/>
  • JAVA : @ComponentScan(base-package="패키지이름") 을 등록

Bean으로 등록할 클래스에 @Component annotation을 추가 같은 타입일 경우 @Component("bean"아이디)를 이용

Component 스캔의 대상이 되는 annotation들

  • Component , Service , Repository , Controller
profile
밍키의 개발 일기장

0개의 댓글

관련 채용 정보