2020. 4. 20. 01:03
기존의 자바 프로그램 작성시에 다른 클래스의 메서드를 사용할 때에
객체를 생성하는 것과 스프링에서 객체를 생성하는 방법의 차이.
기존방식
A.java
public class A
{
public void printA()
{
System.out.println("클래스 A");
}
}
MainClass.java
public class MainClass
{
public static void main(String[] args)
{
A a = new A();
a.printA();
}
}
스프링에서 사용하는 방식
- 클래스 컨테이너에 객체를 생성( xml 파일에 작성)
- 클래스에서 클래스 컨테이너 경로를 잡아줌
- 클래스 컨테이너에서 객체를 얻어옴
applicationContext.xml
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 클래스 모음 / 객체 생성 -->
<bean id="a" class="test.A" />
</beans>
A.java
public class A
{
public void printA()
{
System.out.println("클래스 A");
}
}
MainClass.java
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass
{
public static void main(String[] args)
{
//spring container에 접근 = applicationContext.xml(클래스 컨테이너)
//1. 클래스를 선언해놓은 컨테이너에 접근하기위해 컨테이너 주소를 적어줌
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
//2. 객체를 가져와서 사용
A a = ctx.getBean("a", A.class);
a.printA();
}
}
'Spring Framework > Spring' 카테고리의 다른 글
[Spring] 컨트롤러에서 파라미터를 받는 방법 (0) | 2021.01.07 |
---|---|
[spring] 2. 한글 처리 filter (web.xml) (0) | 2020.06.09 |
[Spring] 의존 주입 - 작성중 (0) | 2020.04.21 |
[spring] - pom.xml 의 dependency (0) | 2020.04.20 |
[spring] - 스프링 프로젝트 생성 (0) | 2020.04.19 |