Thursday 24 May 2018

[Algorithm] Codility Lessson 3-2. Time Complexity - PermMissingElem

Problem


An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
int solution(int A[], int N);
that, given an array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5
the function should return 4, as it is the missing element.
Assume that:
  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1) (not counting the storage required for input arguments).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.






Solution Code


  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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package io.dorbae.study.algorithm.codility.timecomplexity;

/*****************************************************************
 * 
 * PermMissingElem.java
 * 
 * ***************************************************************
 * 
 An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A, returns the value of the missing element.

For example, given array A such that:

  A[0] = 2
  A[1] = 3
  A[2] = 1
  A[3] = 5
the function should return 4, as it is the missing element.

Assume that:

N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1) (not counting the storage required for input arguments).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
 
 
 *
 *****************************************************************
 *
 * @version 0.0.0 2018-05-24 20:30:39 dorbae 최초생성
 * @since 1.0
 * @author dorbae(dorbae.io@gmail.com)
 *
 */
public class PermMissingElem {
 private static final int RESCODE_INVALID = 0;
 private static final int RESCODE_NOTFOUND = 0;
 
 /**
  * 
  * @version 1.1.0 2018-05-24 21:04:11 dorbae empty_and_single 오류 수
  * @version 1.0.0 2018-05-24 20:32:54 dorbae 최초생성
  * @since 1.0.0
  * @author dorbae(dorbae.io@gmail.com)
  *
  * @param A : An array A consisting of N different integers is given
  * @return : Missing element
  */
 public int solution( int[] A) {
  if ( A == null) {
   System.err.println( "Illegal Argument.");
   return RESCODE_INVALID;
  }
  
  int N = A.length;
  
  if ( N < 0 || N > 100000 ) {
   System.err.println( "Illegal Argument.");
   return RESCODE_INVALID;
   
  /** 
   * version 1.1.0
   * Solve empty and single error
  */
  } else if ( N == 0) {
//   return 0; // Old (Error)
   return 1;
   
  }
  /**
   * End of version 1.1.0
   */
  
  boolean[] checkBitArray = new boolean[ N +2]; // Default primitive boolean value is false.
  
  // Checking
  for ( int ll = 0; ll < N; ll++) {
   try {
    if ( checkBitArray[ A[ ll]]) { // Already Checked
     System.err.println( "Already existing value.");
     return RESCODE_INVALID;
    
    } else {
     checkBitArray[ A[ ll]] = !checkBitArray[ A[ ll]];
    
    }
    
   } catch ( IndexOutOfBoundsException e) {
    System.err.println( "each element of array A is an integer within the range [1..(N + 1)]");
    return RESCODE_INVALID;
    
   }
  }
  
  if ( checkBitArray[ 0]) { // one of elements of array A is 0. Each element of array A is an integer within the range [1..(N + 1)]
   return RESCODE_INVALID;
  }
  
  // Find missing element
  for ( int ll = 1; ll < checkBitArray.length; ll++) {
   if ( !checkBitArray[ ll]) {
    return ll;
   }
  }
  
  return RESCODE_NOTFOUND; 
  
    }

}





Result

ver.1.0.0










ver.1.1.0




Wednesday 23 May 2018

[Algorithm] Codility Lessson 1-1. Iterations - BinaryGap

Problem


binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
int solution(int N);
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Assume that:
  • N is an integer within the range [1..2,147,483,647].
Complexity:
  • expected worst-case time complexity is O(log(N));
  • expected worst-case space complexity is O(1).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.








Solution Code


 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
59
60
61
62
63
64
65
66
67
68
package io.dorbae.study.algorithm.codility.iterations;

/*****************************************************************
 * 
 * BinaryGap.java
 * 
 * Task description
 * 
 * A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
 * For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
 * 
 * Write a function:
 * class Solution { public int solution(int N); }
 * that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
 * For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
 * Assume that:
 * N is an integer within the range [1..2,147,483,647].
 * 
 * Complexity:
 * expected worst-case time complexity is O(log(N));
 * expected worst-case space complexity is O(1).
 * Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
 *
 *****************************************************************
 *
 * @version 0.0.0 2018-05-14 23:12:59 dorbae 최초생성
 * @since 1.0
 * @author dorbae(dorbae.io@gmail.com)
 *
 */
public class BinaryGap {
 /**
  * 
  *
  * @version 1.1.0 2018-05-23 23:13:14 dorbae 예외처리. 오류 수
  * @version 1.0.0 2018-05-14 23:12:59 dorbae 최초생성
  * @since 1.0.0
  * @author dorbae(dorbae.io@gmail.com)
  *
  * @param N : positive integer
  * @return : the length of its longest binary gap
  */
 public int solution( int N) {
  if ( N < 1 || N > 2147483647) {
   System.out.println( "N is out of range.");
   return 0;
  }
  
  int maximumInterval = 0;
  int count = 0;
  String binary = Integer.toBinaryString( N);
//  System.out.println( "binary=" + binary);
  char[] checkData = binary.toCharArray();
  for ( int ll = 1; ll < checkData.length; ll++) {
   if ( checkData[ ll] == '1') {
    if ( count > maximumInterval)
     maximumInterval = count;
    count = 0;
    
   } else {
    ++count;
   }
  }
  
  return maximumInterval;
 }
 
}




Result






[Apache Hive] Install Hive2

Requirements

Java Version

- Hive version 1.2부터 Java 1.7 이상 버전이 필요
- Hive version 0.14~1.1까지는 Java 1.6에서도 구동 가능
- Java 1.8을 사용할 것을 권장

Hadoop Version

- Hadoop 2.x 를 권장
- Hadoop 1.x 도 가능하나 Hive 2.0.0 부터 지원 X



1. Download Hive

#> cd /usr/local
#> wget http://mirror.apache-kr.org/hive/hive-2.3.0/apache-hive-2.3.0-bin.tar.gz




2. Unzip Hive Install File

#> tar zxf apache-hive-2.3.0-bin.tar.gz





3. Setup Environment Variables







4. Create Hive Meta Store Directory and Change Mode in HDFS

#> hadoop fs -mkdir /tmp
#> hadoop fs -mkdir /user
#> hadoop fs -mkdir /user/hive
#> hadoop fs -mkdir /user/hive/warehouse
#> hadoop fs -chmod g+w /tmp
#> hadoop fs -chmod g+w /user/hive/warehouse





5. Initialize Schema as DB Type 'derby'

#> schematool -dbType derby -initSchema





6. Start Hive Server

#> hiverserver2 &




[Apache Hive] org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.authorize.AuthorizationException): User: [UserName] is not allowed to impersonate anonymous

When Connect Hive by JDBC driver, This exception occurred.






  • Solution

1. Edit Hadoop Configuration

#> vi $HADOOP_HOME/etc/hadoop/core-site.xml
















2. Format NameNode

#> hadoop namenode -format


3. Restart Hadoop

#> $HADOOP_HOME/sbin/stop-all.sh
#> $HADOOP_HOME/sbin/start-all.sh


4. Restart Hive

[Java] NIO DatagramChannel Tutorial

DatagramChannel Receiver


 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
 *****************************************************************
 * 
 * NIOUDPRecvTest.java
 * 
 * NIO DatagramChannel Receiver
 *
 *****************************************************************
 *
 * @version 1.0.0 2017-10-11 dorbae 최초생성
 * @since 1.0.0
 * @author dorbae
 *
 */
package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class NIOUDPRecvTest {

 /**
  *
  * @version 1.0.0 2017-10-11 dorbae 최초생성
  * @since 1.0.0
  * @author dorbae
  *
  * @param args
  */
 public static void main(String[] args) {
  DatagramChannel channel = null;
  try {
   channel = DatagramChannel.open();
   channel.socket().bind(new InetSocketAddress("localhost", 9000));

  } catch (IOException e) {
   e.printStackTrace();
   System.exit(1);
  }
  
  ByteBuffer buf = ByteBuffer.allocate(256);
  byte[] buffer = new byte[256];
  int limit = 0;
  try {
   while (true) {
    buf.clear();
    try {
     System.out.println("\nWaiting...");
     channel.receive(buf);
     limit = buf.limit();
     System.out.println("buf.limit()=" + limit);
     System.out.println("buf.capacity()=" + buf.capacity());
     System.out.println("buf.position()=" + buf.position());
     System.out.println("buf.arrayOffset()=" + buf.arrayOffset());

     buf.flip();
     limit = buf.limit();
     System.out.println("buf.limit()=" + limit);

     buf.get(buffer, 0, limit);

     System.out.println("data=" + new String(buffer, 0, limit, "utf8"));

    } catch (IOException e) {
     break;
    }

   }

  } catch (Exception e) {
   e.printStackTrace();
  
  } finally {
   if (channel != null)
    try {
     channel.close();
    } catch (IOException e) {}
  }
  
 } 

}



DatagramChannel Sender


 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
/**
 *****************************************************************
 * 
 * NIOUDPSendTest.java
 * 
 * NIO DatagramChannel Sender
 *
 *****************************************************************
 *
 * @version 1.0.0 2017-10-11 dorbae 최초생성
 * @since 1.0.0
 * @author dorbae
 *
 */
package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class NIOUDPSendTest {

 /**
  *
  * @version 1.0.0 2017-10-11 dorbae 최초생성
  * @since 1.0.0
  * @author dorbae
  *
  * @param args
  * @throws IOException 
  */
 public static void main(String[] args) throws IOException {
  String message = "한글 String to write to file..." + System.currentTimeMillis();

  
  DatagramChannel channel = DatagramChannel.open();
  
  
  ByteBuffer buf = ByteBuffer.allocate(256);
  buf.clear();
  buf.put(message.getBytes("utf8"));
  buf.flip();

  int bytesSent = channel.send(buf, new InetSocketAddress("localhost", 9000));

 }

}

[MySQL/MariaDB] Can't init tc.log




1. cd /var/lib/mysql






2. Remove tc.log file and start server

[Algorithm] Codility Lessson 3-1. Time Complexity - FrogJmp

Problem


A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10 Y = 85 D = 30
the function should return 3, because the frog will be positioned as follows:
  • after the first jump, at position 10 + 30 = 40
  • after the second jump, at position 10 + 30 + 30 = 70
  • after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:
  • X, Y and D are integers within the range [1..1,000,000,000];
  • X ≤ Y.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.




Solution Code

 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package io.dorbae.study.algorithm.codility.timecomplexity;

import java.math.BigDecimal;

/*****************************************************************
 * 
 * FrogJmp.java
 * 
 * 120m
 * 1Task
 * 
 * A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

class Solution { public int solution(int X, int Y, int D); }

that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:

X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Complexity:

expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
 *
 *****************************************************************
 *
 * @version 0.0.0 2018-05-23 15:27:59 dorbae 최초생성
 * @since 1.0
 * @author dorbae(dorbae.io@gmail.com)
 *
 */
public class FrogJmp {

 /**
  * 
  *
  * @version 1.0.0 2018-05-23 15:28:51 dorbae 최초생성
  * @since 1.0.0
  * @author dorbae(dorbae.io@gmail.com)
  *
  * @param X : current position
  * @param Y : a smallest position where the frog wants to go
  * @param D : a distance that the frog can jump
  * @return : the minimal count to the frog should jump
  */
 public int solution( int X, int Y, int D) {
  // Exception
  if ( X < 1 || X > 1000000000) {
   System.err.println( "X is out of allowed range.");
   return 0;
   
  } else if ( Y < 1 || Y > 1000000000) {
   System.err.println( "Y is out of allowed range.");
   return 0;
   
  } else if ( D < 1) {
   System.err.println( "Invalid D.");
   return 0;
   
  }
  
  int gap = Y - X;
  if ( gap < 1) {
   return 0;
  }
  
  BigDecimal gapDecimal = new BigDecimal( ( double)gap);
  BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D), BigDecimal.ROUND_UP);
  
  return diviedeDecimal.intValue();
  
 }
 
}



Result



[Java] java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result

ErrorCode

BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D));


When use divide method, you should set rounding mode and digit. For example, a result of '10 / 3' is 3.33333.... And can't not represent digit.

From the Java 5 docs (Java 8 docs here):
When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)
As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.
If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

Soluition


BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D), BigDecimal.ROUND_UP);
BigDecimal diviedeDecimal = gapDecimal.divide( new BigDecimal( D), 3, BigDecimal.ROUND_UP);



Friday 11 May 2018

[Spring] 토비의 스프링 1장 내용 정리


개방폐쇄원칙(OCP, Open-Closed Principle)

로버트 마틴이 정리한 객체지향 설계 원칙 (SOLID)
‘Java 프로그래머를 위한 UML 실전에서는 이것만 쓴다’ - 마틴
SRP (The Single Responsibility Principle) : 단일 책임 원칙
OCP (The Open Closed Principle) :  개방 폐쇄 원칙
LSP (The Liskov Subsititution Principle) : 리스코프 치환 원칙
ISP (The Interface Segregation Principle) : 인터페이스 분리 원칙
DIP (The Dependency Inversion Principle) : 의존관계 역전 원칙

스프링은 객체지향적 설계 원칙과 디자인 패턴에 나타난 장점을 자연스럽게 개발자들이 활용할 있게 해주는 프레임워크

IoC (Inversion of Control) : 제어의 역전
서블릿도 제어의 역전 개념이 적용된 예로 있다. 서블릿 안에 main() 메소드 없이 컨테이너가 적절한 시점에 서블릿 클래스의 오브젝트를 만들고 안의 메소드를 호출


Factory : 디자인패턴의 팩토리 패턴 x. 컴포넌트 역할을 하는 오브젝트들을 설계하는 역할

Bean : 스프링이 제어권을 가지고 직접 만들고 관계를 부여하는 오브젝트 (컴포넌트)
Bean Factory : 빈의 생성과 관계설정 같은 제어를 담당하는  IoC 오브젝트 => Application Context

@Configuration : 팩토리를 위한 오브젝트 설정을 담당하는 클래스 지정
@Bean : 오브젝트(컴포넌트) 만들어 주는 메소드에 지정


  • 빈(bean)

:스프링이 IoC 방식으로 관리하는 오브젝트. managed object(관리되는 오브젝트) 라고도 부름. 모든 오브젝트가 빈은 아님. 스프링이 직접 생성과 제어를 담당하는 오브젝트만 해당
  • 팩토리(bean factory)

스프링의 IoC 담당하는 핵심 컨테이너. 등록/생성/조회 관리 기능 담당. 보통은 바로 사용하지 않고, 이를 확장한 애플리케이션 컨텍스트를 이용
  • 애플리케이션 컨텍스트(application context)

팩토리를 확장한 IoC  컨테이너. 관리 기본 기능은 팩토리와 동일. 외에 스프링이 제공하는 각종 부가 서비스를 추가로 제공. 팩토리는 빈의 생성과 제어의 관점에서 이야기, 애플리케이션 컨텍스트는 스프링이 제공하는 애플리케이션 지원 기능을 모두 포함. ApplicationContext 인터페이스는 BeanFactory 상속.
  • 설정정보/설정 메타정보(configuration metadata)

애플리케이션 컨텍스트 또는 팩토리가 IoC 적용하기 위해 사용하는 메타정보. IoC 컨테이너에 의해 관리되는 애플리케이션 오브젝트를 생성하고 구성할 사용. (=청사진(blueprints))
  • 컨테이너(Container) / IoC 컨테이너

IoC  방식으로 빈을 관리한다는 의미에서 애플리케이션 컨텍스트나 팩토리를 컨테이너 또는 IoC 컨테이너라고도 한다.

오브젝트의 동일성(identity) 동등성(equality)
메모리상에 하나의 오브젝트만 존재하고, 개의 레퍼런스 변수를 갖고 있는 것을 동일성. 동등성은 메모리 상의 개의 서로 다른 오브젝트가 존재하지만 오브젝트의 정보가 동등함을 의미.
equals() 메소드를 오버라이드하지 않으면 Object equals() 메소드를 사용. 이는 동일성을 비교해서 결과를 리턴.


싱글톤 레지스트리로서의 애플리케이션 컨텍스트
서버 애플리케이션은 대용량 트랜잭션에 대해서 오브젝트를 생성하기 때문에 싱글톤으로 관리. 서블릿 또한 대부분 멀티쓰레드 환경에서 싱글톤으로 동작.

싱글톤 패턴 (Singleton Pattern)
  1. private 생성자를 갖고 있기 때문에 상속할 없음
  2. 테스트하기 힘듦
  3. 서버환경에서 클래스 로더를 어떻게 구성하고 있느냐에 따라서 싱클톤 크래스임에도 하나 이상의 오브젝트가 만들어질 있음
  4. 전역 상태를 만들 있기 때문에 위험성이 있음

다중 사용자의 요청을 한꺼번에 처리하는 스레드들이 동시에 싱글톤 오브젝트의 인스턴스 변수를 수정하는 것은 매우 위험. 그렇기 때문에 싱글톤이 멀티스레드 환경에서 서비스 형태의 오브젝트로 사용되는 경우에는 상태정보를 내부에 갖고 있지 않은 무상태(stateless) 방식으로 만들어져야

빈의 스코프
빈이 생성되고, 존재하고, 적용되는 범위.
  • 싱글톤 : 스프링 빈의 기본 스코프. 컨테이너 내에 개의 오브젝트만 만들어져, 강제로 제거하지 않는 스프링 컨테이너가 존재하는 동안 계속 유지
  • 프로토타입 : 컨테이너에 빈을 요청할 때마다 매번 새로운 오브젝트 생성.
  • 요청 : 웹을 통해 새로운 HTTP 요청이 생길 때마다 생성
  • 세션 : 웹의 세션과 유사

의존관계 검색 (dependency lookup)
의존관계를 맺는 방법이 외부로부터의 주입이 아니라 스스로 검색을 이용. 런타임 의존관계를 맺을 오브젝트를 결정하는 것과 오브젝트의 생성 작업은 외부 컨테이너에게 IoC 맡기지만, 이를 가져올 때는 메소드나 생성자를 통한 주입 대신 스스로 컨테이너에게 요청하는 방법을 사용

XML 설정
<beans> -> @Configuration
<bean> -> @Bean
<property> -> 수정 메소드 DI. name, ref 라는 개의 애트리뷰트를 갖음. name : 프로퍼티의 이름. ref : 수정자 메소드를 통해 주입할 오브젝트의 이름
<beans>
<bean id=“methodName” class=“a.b.c…BeanClass” />
</beans> 
userDao.setConnectionMaker(connectionMaker()); -> <property name=“connectionMaker” ref=“connectionMaker” />
<bean id=“userDao” class=“io.dorbae.study.spring.dao.UserDao”>
<property name=“connectionMaker” ref=“connectionMaker” />
<bean>



소스코드 다운로드