스프링 객체 생성 방법
1. XML 기반 (옛날 방식)
2. 어노테이션 기반 (요즘 방식)
1. XML 기반의 객체 생성 (환경설정)
- 스프링 설정파일을 이용한 객체 생성
xml 설정파일
<bean id ="사용 할 id" class="제공 할 클래스명" />
<bean id ="m" class="exam03.MessageBeanEn" />
- 생성된 객체 사용하기 1 (BeanFactory)
- 최상위 클래스로 Resource가 필요하다
Main
Resource resource = new FileSystemResource("설정 파일 명.xml");
BeanFactory factory = new XmlBeanFactory(resource);
인터페이스명 m = ("인터페이스로 형변환")factory.getBean("설정한 객체명");
설정한 객체명.호출할 함수("");
Resource resource = new FileSystemResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
MessageBean m = (MessageBean)factory.getBean("m");
m.sayHello("tiger");
- 생성된 객체 사용하기 2 (ApplicationContext)
- BeanFactory를 상속받은 클래스
- Resource가 필요 없음
- classPath를 기준으로 xml의 위치를 표현 가능
ApplicationContext ac = new ClassPathXmlApplicationContext("패키지명/설정파일.xml");
ApplicationContext ac = new ClassPathXmlApplicationContext("diTest04/beans01");
Person p = (Person)ac.getBean("p");
p.info();
2. 어노테이션(@) 기반의 객체 생성
- @Configuration 어노테이션을 추가 한 상태로 @Bean 어노테이션을 추가하면 Bean을 등록할 수 있다.
- 자바 클래스를 이용
설정용 .class 파일
@Configuration -> 환경 설정의 의미
public class 클래스이름{
@Bean
public 생성할클래스 id입력()
{
return new 생성할클래스();
}
}
------------- 같은 의미 ------------------
<bean id="id입력" class="생성할클래스">
main 파일
ApplicationContext context = new AnnotationConfigApplicationContext (클래스이름);
반응형
'개발 > 스프링(Spring)' 카테고리의 다른 글
(Spring) @ReqeustMapping GET/POST 방식 설정 (0) | 2022.06.05 |
---|---|
(Spring) MVC (0) | 2022.06.02 |
(Spring) Bean 범위(scope) 설정 (0) | 2022.05.31 |
Spring (0) | 2022.05.30 |
(Spring) 의존관계 설정 방법 (0) | 2022.05.26 |
댓글