객체간의 의존관계를 자신이 아닌 외부조립기가 수행해준다는 개념.
Spring은 객체를 Bean으로 관리
즉, 의존성을 주입.
XML파일에서 의존에 필요한 것들을 만들어내고, JAVA파일의 Setter와 Contructor에서 받아 사용할 수 있게 됨.
<bean>
<constructor-arg>
<value></value>
</constructor-arg>
<constructor-arg value="문자"/>
</bean>
컨스트럭터에 넣을 때
bean 을 등록할 때 <constructor-arg>가 존재하지 않으면 무조건 기본생성자를 생성한다. <property name=""> 여기서 property 의 속성 name은 등록한 class에 존재하는 setter 메서드의 이름이다. 즉 name은 setName() 메서드의 'Name' . setter 메서드의 set을 없애고 첫글자를 대문자로 바꾼 단어가 property 의 속성 name의 value가 되는 것이다.
그러니까 개발은 많은 수정을 필요로하지. 따라서 필요없어지는 경우도 생기고 잠깐 제외되는 경우도, 추가되는 경우도 생겨, 그럴때마다 일일히 의존성을 모두 고려해서 되고 안되고를 따지는 것이 아니라
연결 자체를 느슨하게 즉 연결고리를 담담하는 과정을 만들었다고 생각하면 될 것 같아.
이는 Xml을 통해서도 JAVA 파일을 통해서도 가능한데.
XML을 사용할 경우 위의 경우 처럼
context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
이렇게 작성하면 되고
JAVA 파일을 사용할 경우
AnnotationConfigApplicationContext(Configurations.class);
이런식으로 작성해야해 근데 JAVA파일의 경우 Pom에서 CGlib의 버전을 3.0 이상으로 맞춰야 컴파일러가 인식하는 것 같더라.
POJO(Plain Old Java Object) Servlet과 EJB 등 Interface에 종속적이지 않은 모든 자바 클래스를 말하며 자바빈은 모두 POJO이다.
싱글톤
public class MessageService{
private static MessageService instance;
private MessageService(){}
public static MessageService getInstance(){
if(instance==null){
instance=new MessageService();
}
}
}
Spring에서는 그냥 xml통한 bean선언을 해주면 되는 것 같아
싱글톤이란;
하나의 프로그램 내에서 하나의 인스턴스만을 생성해야만 하는 상황. 예를 들어 환경설정을 관리하는 클래스나 Connection Pool, Thread Pool과 같이 풀(Pool) 형태로 관리되는 클래스의 경우 프로그램 내에서 단 하나의 인스턴스로 관리되는 것이 일반적이며, 이 때 Singleton 패턴을 적용하는 것이 일반적인 경우라고 볼 수 있다.
싱글톤은 하나의 개만이 선언되어 이를 같이 나눠쓰지만,
프로토 타입은 빈이 선언될 때 마다 만들어져서 모두 따로 씀.
- 빈의 범위 설정은 <bean>의 속성인 scope로 설정할 수 있다.
- 아래 예제에서 첫번째 빈은 scope을 설정 하지 않았는데 이렇게 명시되지 않을 경우엔 싱글톤이 기본으로 지정된다.
- 두번째 빈에는 scope을 prototype으로 지정하였다. 이 타입은 위의 표에 명시했듯이 getBean()을 호출시마다 빈이 새로 생성된다.
전형적인 DAO는 주고받는 어떤 상태도 가지지 않기 때문에 데이터 접근 객체 (DAO)는 보통 프로토타입으로 설정하지 않는다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hyundaiEngine" class="exam.test14.Engine"
p:maker="Hyundai" p:cc="1997"/>
<bean id="kiaEngine" class="exam.test14.Engine"
p:maker="Kia" p:cc="3000"
scope="prototype"/>
</beans>
package exam.test14;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("exam/test14/beans.xml");
System.out.println("[singleton 방식(기본)]-------------------------");
Engine e1 = (Engine) ctx.getBean("hyundaiEngine");
Engine e2 = (Engine) ctx.getBean("hyundaiEngine");
System.out.println("e1-->" + e1.toString());
System.out.println("e2-->" + e2.toString());
if (e1 == e2) {
System.out.println("e1 == e2");
}
System.out.println("[prototype 방식]-------------------------");
Engine e3 = (Engine) ctx.getBean("kiaEngine");
Engine e4 = (Engine) ctx.getBean("kiaEngine");
System.out.println("e3-->" + e3.toString());
System.out.println("e4-->" + e4.toString());
if (e3 != e4) {
System.out.println("e3 != e4");
}
}
}
[singleton 방식(기본)]-------------------------
e1-->[Engine:Hyundai,1997]
e2-->[Engine:Hyundai,1997]
e1 == e2
[prototype 방식]-------------------------
e3-->[Engine:Kia,3000]
e4-->[Engine:Kia,3000]
e3 != e4
또한 Bean을 통하여 상속관계 설정도 가능하다.
예를 들면.
public class Test1 {
private String message1;
public void setMessage1(String message1) {
this.message1 = message1;
}
public void getMessage1() {
System.out.println("Your Message1 : " + message1);
}
}
public class Test2 {
private String message1;
private String message2;
public void setMessage1(String message1) {
this.message1 = message1;
}
public void getMessage1() {
System.out.println("Your Message1 : " + message1);
}
public void setMessage2(String message2) {
this.message2 = message2;
}
public void getMessage2() {
System.out.println("Your Message2 : " + message2);
}
}
이런 구조에서
<bean id="Test1" class="Hello.Test1" scope="singleton">
<property name="message1" value="Hello World!" />
</bean>
<bean id="Test2" class="Hello.Test2" scope="singleton" parent="Test1">
<property name="message2" value="Hello World2!" />
</bean>
이런식으로 구성하면 출력할 때,
Test2는 Test1에서 상속받은 message1을 갖고있게된다.
'IT > Spring' 카테고리의 다른 글
Spring Annotation 설명 및 예제 (0) | 2015.01.31 |
---|---|
Spring MVC 예제 (0) | 2015.01.30 |
Spring에서 excel 사용하기 JXL & POI 개념 및 예제 (2) | 2015.01.23 |
Spring JDBC framework 개념 및 예제 (0) | 2015.01.22 |
Spring 이론 (0) | 2015.01.20 |