Spring_스프링 프레임워크_스프링을 이용한 의존성 주입하기
- 스프링을 이용한 의존성 주입하기
- day01 > sts.day01.exam02 패키지를 sts.day01.exam03으로 복사합니다.
- web > WEB-INF > lib 폴더에 기본 spring을 위한 jar 파일 추가합니다.
- commons-logging-1.2.jar
- spring-beans-5.3.27.jar
- spring-context-5.3.27.jar
- spring-core-5.3.27.jar
- spring-expression-5.3.27.jar
- spring-jcl-5.3.27.jar
- new > Source Folder
- 이름 : srcmain/resources
> Finish
- srcmain/resources 폴더에 새로운 spring bean 파일 생성하기
- new > Spring Bean Configuration File
- 이름 : applicationContext.xml
> next
- XSD namespace declarations : beans 선택
- Select desired XSD : '4.3.xsd'선택
<bean id="지정할 변수" class="패키지 명부터 가져올 클래스 이름" />
=====
1
2
3
4
5
6
7
8
9
|
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="myBean" class="sts.day01.exam03.MyBeanOne" />
<bean id="myBean2" class="sts.day01.exam03.MyBeanTwo" />
</beans>
|
- sts.day01.exam03 > HelloSpring.java 클래스 생성
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package sts.day01.exam03;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class HelloSpring {
public static void main(String[] args) {
// 스프링 설정파일_applicationContext.xml 파일을 참조하는 객체를 생성합니다.
AbstractApplicationContext factory = new GenericXmlApplicationContext("applicationContext.xml");
// myBean 라고 id를 지정한 클래스를 가지고 옵니다.
MyBean bean = (MyBean)factory.getBean("myBean");
bean.sayHello("Spring");
// myBean2 라고 id를 지정한 클래스를 가지고 옵니다.
MyBean bean2 = (MyBean)factory.getBean("myBean2");
bean2.sayHello("Spring2");
// 사용한 메모리를 반환합니다.
factory.close();
}
}
|