그 외 공부/SPRING

spring framework[5] - life cycle and scope, 외부파일을 이용한 설정

ssangeun 2018. 1. 9. 20:54

# 컨테이너 생명 주기

1
2
3
4
5
6
7
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); //생성
ctx.load("classpath:applicationCTX.xml"); //설정
ctx.refresh(); 
        
        /* 사용 */
        
ctx.close();
cs

 

 파라미터가 없는 생성자를 이용하여 생성을 하고 설정(load())을 따로 해준다면 refresh()함수를 반드시 사용한다.

 

# 스프링 빈 생명 주기

- InitializingBean을 상속할경우 : afterPropertiesSet()을 오버라이딩하고 빈 초기화 과정에서 호출 (ctx.refresh())

- DisposableBean을 상속할경우 : destroy()를 오버라이딩하고 빈 소멸 과정에서 생성 (ctx.close())

 

# 스프링 빈 범위(scope) - 해당하는 객체가 어디까지 영향을 미치는지 결정하는 것

- 빈의 기본값은 "singleton"

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
26
27
28
package com.javalec.ex;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
        Student student1 = ctx.getBean("student", Student.class);
        System.out.println(student1.getName());
        System.out.println(student1.getAge());
        
        Student student2 = ctx.getBean("student", Student.class);
        student2.setName("이상은");
        student2.setAge(25);
        System.out.println(student2.getName());
        System.out.println(student2.getAge());
        
        if(student1.equals(student2)) {
            System.out.println("the same");
        }else {
            System.out.println("different");
        }
    }
 
}
cs

 

 => "student1"과 "student2"는 동일한 객체이다.

 


# Environment 객체 - jsp 프로그래밍에서는 DB정보들을 모두 자바 코드에 명시를 하였는데 만약 DB의 정보의 변화(DB의 주소 이전, 리뉴얼로 인한 삭제)가 발생할 경우에는 외부파일로 생성하여 사용해야한다, 이 경우 environment객체는 외부파일을 가져와서 프로퍼티를 추가하거나 추출하는 역할을 한다.

 MainClass.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
26
27
28
29
30
31
32
33
34
35
36
37
package com.javalec.ex;
 
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.support.ResourcePropertySource;
 
public class MainClass {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConfigurableApplicationContext ctx = new GenericXmlApplicationContext();
        ConfigurableEnvironment env = ctx.getEnvironment();
        MutablePropertySources propertySources = env.getPropertySources();
        
        try {
            propertySources.addLast(new ResourcePropertySource("classpath:admin.properties"));
            
            System.out.println(env.getProperty("admin.id"));
            System.out.println(env.getProperty("admin.pw"));
        }catch(Exception e) {}
        
        GenericXmlApplicationContext gctx = (GenericXmlApplicationContext)ctx;
        gctx.load("applicationCTX.xml");
        gctx.refresh();
        
        AdminConnection adminConnection = gctx.getBean("adminConnection", AdminConnection.class);
        System.out.println("admin id : "+adminConnection.getAdminId());
        System.out.println("admin pw : "+adminConnection.getAdminPw());
        
        gctx.close();
        ctx.close();
    }
 
}
 
cs

 

 

 AdminConnection.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.javalec.ex;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
 
public class AdminConnection implements EnvironmentAware, InitializingBean, DisposableBean{
    private Environment env;
    private String adminId;
    private String adminPw;
    
    @Override
    public void setEnvironment(Environment env) {
        // TODO Auto-generated method stub
        setEnv(env);
    }
 
    public Environment getEnv() {
        return env;
    }
 
    public void setEnv(Environment env) {
        this.env = env;
    }
 
    public String getAdminId() {
        return adminId;
    }
 
    public void setAdminId(String adminId) {
        this.adminId = adminId;
    }
 
    public String getAdminPw() {
        return adminPw;
    }
 
    public void setAdminPw(String adminPw) {
        this.adminPw = adminPw;
    }
 
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("destroy()");
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("afterPropertiesSet()");
        setAdminId(env.getProperty("admin.id"));
        setAdminPw(env.getProperty("admin.pw"));
    }
    
}
 
cs

 

 admin.properties

 

1
2
admin.id=sangeun
admin.pw=1234
cs

 

 applicationCTX.xml

 

1
2
3
4
5
6
7
8
<?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="adminConnection" class="com.javalec.ex.AdminConnection"/>
</beans>
 
cs

 

 

# Environment객체를 사용하지 않고 프로퍼티 파일을 이용한 설정

 MainClass.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.javalec.ex;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
        
        AdminConnection connection = ctx.getBean("adminConnection", AdminConnection.class);
        System.out.println("admin id : "+connection.getAdminId());
        System.out.println("admin pw : "+connection.getAdminPw());
        System.out.println("sub admin id : "+connection.getSub_adminId());
        System.out.println("sub admin pw : "+connection.getSub_adminPw());
        
        ctx.close();
    }
 
}
cs

 

AdminConnection.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.javalec.ex;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
 
public class AdminConnection implements InitializingBean, DisposableBean{
    private String adminId;
    private int adminPw;
    private String sub_adminId;
    private int sub_adminPw;
    
    public String getAdminId() {
        return adminId;
    }
    public void setAdminId(String adminId) {
        this.adminId = adminId;
    }
    public int getAdminPw() {
        return adminPw;
    }
    public void setAdminPw(int adminPw) {
        this.adminPw = adminPw;
    }
    public String getSub_adminId() {
        return sub_adminId;
    }
    public void setSub_adminId(String sub_adminId) {
        this.sub_adminId = sub_adminId;
    }
    public int getSub_adminPw() {
        return sub_adminPw;
    }
    public void setSub_adminPw(int sub_adminPw) {
        this.sub_adminPw = sub_adminPw;
    }
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("destory");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("afterproperties set");
    }
    
}
 
cs

 

admin.properties

sub_admin.properties 

 

1
2
admin.id=sangeun
admin.pw=1234

cs

1
2
admin.id=sangeun
admin.pw=1234

cs

 

 applicationCTX.xml

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
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
    <context:property-placeholder location="classpath:admin.properties, classpath:sub_admin.properties"/>
    
    <bean id="adminConnection" class="com.javalec.ex.AdminConnection">
        <property name="adminId">
            <value>${admin.id}</value>
        </property>
        <property name="adminPw">
            <value>${admin.pw}</value>
        </property>
        <property name="sub_adminId">
            <value>${sub_admin.id}</value>
        </property>
        <property name="sub_adminPw">
            <value>${sub_admin.pw}</value>
        </property>
    </bean>
 
</beans>
cs

 

# annotation을 이용한 설정

 

 

 

# profile 속성을 이용한 설정 - 동일한 스프링 빈을 여러 개 만들어 놓고 상황에 따라서 적절한 스프링 빈을 사용할 수 있다.