@Component

  • Spring에서 관리하는 객체임을 표사하기 위해 사용하는 가장 기본적인 어노테이션
  • scan-auto-detection 과 dependency injection을 사용하기 위해서 사용되는 가장 기본 어노테이션
  • 컨포넌트에 클르스들에 포괄적으로 @Component를 붙일 수 있지만, @Repository, @Service, @Controller의 역할을명시적으로 구분해서 써주는 것을 추천

 

@Repository

  •  DB에 접근하는 코드

 

@Service

  • DB에 접근하는 코드의 repository에 위임
  • 비지니스 로직과 관련된 모든 코드

 

@Controller

  • 클라이언트로부터 요청이 들어왔을 때, dispatcherservlet이 handleradapter를 통해 컨트롤러를 찾기 위해 '컨트롤러' 역할을 한다고 명시
  • Web MVC 코드에서 사용되는 어노테이션
  • 해당 컨트롤러 밑에서만 @RequestMapping 어노테이션 사용 가능

 

 

 

 

1) 생명주기 ( Life Cycle) 란 ?

  • 스프링 빈은 스프링 컨테이너 내부에서 생성되고, 스프링이 종료되기 전까지 생명주기 ( Life Cycle) 를 갖는다
  • 이때, 스프링은 객체 생성 -> 의존관계 주입의 라이프 사이클을 갖는다

 

생성 - 설정 - 사용 - 소멸

 

  • 생성

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();

 

컨테이너와 빈 객체 동시 생성 방법

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appCtx.xml");

 

  • 설정

 

  • 사용

getBean()을 이용한 Bean 객체 사

BookRegisterService bookRegisterService = ctx.getBean("bookRegisterService", BookRegisterService.class);

BookSearchService bookSearchService = ctx.getBean("bookSearchService", BookSearchService.class);

  • 종료

close() 를 이용한 컨테이너 종료

bean 도 함께 소멸

 

ctx.close();

 

 

2) Bean 객체 생명 주기

  • Bean 객체의 생명주기는 스프링 컨테이너의 생명주기와 동일하다
  • 스프링 컨테이너를 생성할때 Bean이 같이 생성되고, getBean()은 생성된 Bean 객체를 불러오는 것

 

3) Bean 객체 생명 주기 사용법

1. interface 활용

  • <interface> InitializingBean 에서 afterPropertiesSet 을 제공 (bean 객체 생성 시 호출)
  • <interface> DisposableBean 에서 destroy 를 제공 (bean 객체 소멸 시 호출)

 

2. init-method, destory-method 속성 활용

 

 

- 스프링 설정 파일 appCtx.xml

<bean id="bookRegisterService" class="com.brms.book.service.BookRegisterService"

init-method="initMethod" destroy-method="destroyMethod"/>

 

 

- BookRegisterService.java

public class BookRegisterService {

 

@Autowired

private BookDao bookDao;

 

public BookRegisterService() { }

 

public void register(Book book) {

bookDao.insert(book);

}

 

public void initMethod() {

System.out.println("BookRegisterService 빈(Bean)객체 생성 단계");

}

 

public void destroyMethod() {

System.out.println("BookRegisterService 빈(Bean)객체 소멸 단계");

}

}

 

 

3.@PostConstruct, @PreDestory 어노테이션 활용

 

의존객체 자동 주입이란 ?

  • 스프링 설정 파일에서 의존객체를 주입할때 <construct-org> 또는 <property> 태그로 의존 대상 객체를 명시하지 않아스프링 컨테이너가 자동으로 필요한 객체를 찾아서 의존 대상 객체가 필요한 객체에 주입해 주는 기능
  • 구현방법으로 @Autowired, @Resource, @inject 어노테이션을 사용

 

의존객체 자동 주입을 사용하려면 스프링 설정 파일에 <context:annotation-config />  추가해줘야함

 

@Autowired

  • 주입하려고 하는 객체의 타입이 일치하는 객체를 자동으로 주입
  • @Resource 보다 사용할 수 잇는 범위가 넓다
  • 사용할 수 있는 위치 : 맴버 변수, setter 메소드, 생성자, 일반 메소드

-스프링 설정 파일 appCtx.xml

<context:annotation-config />

<bean id="wordDao" class="com.word.dao.WordDao" >

</bean>

 

-WordRegisterServiceUseAutowired.java

@Autowired

private WordDao wordDao;

 

 

@Autowired 사용시 주의할점

  • @Autowired는 동일한 타입의 빈이 2개 이상일 경우 스프링 컨테이너는 자동 주입 대상 객체를 판단하지 못해서 Exception 발생시킴
  • 이를 해결하기 위해 @qualifier 사용
  • 단, 동일한 타입의 빈이 여러 개 존재할 경우 기본적으로 참조 변수의 이름과 동일한 빈을 찾아서 주입한다.
  • 아래 예시와 같이 동일한 타입을 빈이 3가지 있는 상황에서 그냥 실행시키면 에러가 발생하지만 bean id 중  wordDao  가 있다면 참조 변수의 이름과 동일한 빈이 있어 오류가 발생하지 않는다 

 

- appCtx.xml

<context:annotation-config />

 

<bean id="wordDao1" class="com.word.dao.WordDao" >

    <qualifier value="usedDao"/>

</bean>

<bean id="wordDao2" class="com.word.dao.WordDao" />

<bean id="wordDao3" class="com.word.dao.WordDao" />

 

-WordRegisterServiceUseAutowired.java

@Autowired

@Qualifier("usedDao")

private WordDao wordDao;

 

 

  • 디폴트 생성자 없이 프로퍼티나 메소드에 @Autowired 사용할 경우 에러가 발생하므로 디폴트 생성자를 꼭 명시해줘야함

public WordRegisterServiceUseAutowired() {

// TODO Auto-generated constructor stub

}

 

@Autowired

public WordRegisterServiceUseAutowired(WordDao wordDao) {

this.wordDao = wordDao;

}

 

@Resource

  • 주입하려고 하는 객체의 이름이 일치하는 객체를 자동으로 주입
  • 사용할 수 있는 위치 : 맴버변수, setter 메소드

<context:annotation-config />

 

<bean id="wordDao1" class="com.word.dao.WordDao" >

    <qualifier value="usedDao"/>

</bean>

<bean id="wordDao2" class="com.word.dao.WordDao" />

<bean id="wordDao3" class="com.word.dao.WordDao" />

 

@Resource(value="wordDao1")

private WordDao wordDao;

 

@inject

@Autowired와 비슷하게 의존 객체를 자동으로 주입할 수 있음

@Autowired와 차이점이라면 @Autowired일 경우 required 속성을 사용하여 의존 대상 객체가 없을 경우에도  Exception을 피할 수 있지만, @inject의 경우 required 속성 지원 하지 않음

 

프로젝트를 시작하면서 application.xml 설정을 해주는데

 

<beans xmlns="http://www.springframework.org/schema/beans"

 

xmlns:aop="http://www.springframework.org/schema/aop"

 

xmlns:context="http://www.springframework.org/schema/context"

 

xmlns:security="http://www.springframework.org/schema/security"

 

xmlns:tx="http://www.springframework.org/schema/tx"

 

xsi:schemaLocation="

 

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

 

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

 

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

 

http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd

 

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

 

xsi:schemaLocation 에서 Downloading external resources is disabled. 오류가 발생했다

 

 

첫번째로 검색했던 블로그에서는  <beans xmlns:beans:   <beans xmlns: 로 고치면 된다고 했는데

난 이미 <beans xmlns: 로 작성했었다.

 

그래서 난 반대로 <beans xmlns: 뒤에 <beans xmlns:beans: 으로 수정해 줬더니 해당 오류는 사라졌지만

아래와 같은 새로운 오류가 발생했다.

 

cvc-elt.1.a: cannot find the declaration of element 'beans'.

 

처음에는 버전을 안적어줘서 그런가 해서 버전을 적어줘도 오류는 똑같았다

 

그래서 두번째로 수정했던 부분을 지웠다. 잘못 수정했다는 생각이 들어 다른 해결방안을 찾았다

 

다시 첫번째 오류에 집중하였는데 소스 다운에 문제 있다고 하니

 

Preferences -> Maven -> Download Artifact JavaDoc 체크를 해주었다.

 

체크해주니 정상 작동하였다.

 

 

아래 링크를 참고하였다

https://stackoverflow.com/questions/77252112/downloading-from-external-resources-is-disabled-in-hibernate-dtd

 

Downloading from external resources is disabled in hibernate dtd

While I am trying to do hibernate configuration I put hibernate dtd in hibernate.cfg.xml file and it is showing an error that downloading from external resources is disabled. Can you please help me...

stackoverflow.com

 

 

 

 

+ Recent posts