1차원 배열 추가 및 삭제

 

 

 1차원 배열 추가

 

'''
   1차원 배열 추가
   1) np.append(arr, 값, axis=0)
    ==> 값 추가해서 새로운 벡터 반환
    ==> axis=0이 기본이고 행축을 고정한다는 의미이다.
       따라서 열이 추가됨
   2) np.insert(arr, 위치(idx|fancy), 값, axis=0)

'''
import numpy as np
list_value= [10,20,30,40,50]
arr = np.array(list_value)
print(arr)

# 1) np.append(arr, 값, axis=0)
arr2 = np.append(arr, 100)
print(arr2) # [ 10  20  30  40  50 100]
print("원보:", arr) # [10 20 30 40 50]

arr2 = np.append(arr, [100,300])
print(arr2) # [ 10  20  30  40  50 100 300]

# 2) np.insert
list_value= [10,20,30,40,50]
arr = np.array(list_value)
arr2 = np.insert(arr,0, 100) # 색인: 인덱싱
print(arr2) # [100  10  20  30  40  50]
arr2 = np.insert(arr,[0,2], 100) # 색인: fancy 색인(정수형 색인)
print(arr2) # [100  10  20 100  30  40  50]

arr2 = np.insert(arr,[0,2,1], 100) # 색인: fancy 색인(정수형 색인)
print(arr2) # [100  10 100  20 100  30  40  50]

* 출력 화면

 1차원 배열 삭제

 

'''
   1차원 배열 삭제
   1) np.delete(arr, 위치(idx|fancy|np.s_[s:e]), axis )


'''
import numpy as np

list_value= [10,20,30,40,50]
arr = np.array(list_value)
print(arr)

arr2 = np.delete(arr, 0)  # 색인: 인덱싱
print(arr2) # [20 30 40 50]

arr2 = np.delete(arr, -1)  # 색인: 인덱싱
print(arr2) # [20 30 40 50]

arr2 = np.delete(arr, [0,2,3])  # 색인: fancy 색인(정수형 색인)
print(arr2) # [20 50]

arr2 = np.delete(arr, [0,2,-1])  # 색인: fancy 색인(정수형 색인)
print(arr2) # [20 40]

# 슬라이싱 삭제
list_value= [10,20,30,40,50]
arr = np.array(list_value)

arr2 = np.delete(arr, np.s_[1:4])  # 색인: 슬라이싱 ==>  np.s_[s:e]
print(arr2) # [20 30 40 50]

* 출력 화면

 

 출처

 

 

+ 강의 교재

'AI Bootcamp > Numpy' 카테고리의 다른 글

[Numpy] 1일차_1차원 배열 생성  (0) 2022.04.19
[Numpy] 1일차_0차열 배열  (0) 2022.04.19

1차원 배열 생성

 

 

 1차원 배열 생성_Vector1_array 함수

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)

'''
import numpy as np

# 1. 벡터 생성
list_value= [10,20,30]
vector_value = np.array(list_value)

print("list_value:", list_value, type(list_value)) # [10, 20, 30] <class 'list'>
print("vector_value:", vector_value, type(vector_value)) # [10 20 30] <class 'numpy.ndarray'>

* 출력 화면

 

 1차원 배열 생성_Vector2_array 함수2_list와 vector 차이점

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)

'''
import numpy as np

# 1. 벡터 생성
list_value= [10,20,30]
vector_value = np.array(list_value)

print("list_value:", list_value, type(list_value)) # [10, 20, 30] <class 'list'>
print("vector_value:", vector_value, type(vector_value)) # [10 20 30] <class 'numpy.ndarray'>

# 2. 파이썬의 리스트 vs 벡터
# 가. 벡터는 자동으로 형변환이 된다. ==> 반드시 동일한 타입만 저장 가능하다.
list_value= [10,20,30,"A"]
list_value= [10,20,30,4.]
print(list_value)
vector_value = np.array(list_value)
print(vector_value)

# 나. 벡터화 연산: 벡터와 스칼라 연산
list_value= [10,20,30]
result = list_value * 2 # [10, 20, 30, 10, 20, 30]
print("파이썬의 결과:", result)
vector_value = np.array(list_value)
result = vector_value * 2 # [10 20 30] * 2 = [20 40 60] , 벡터화 연산(요소간 연산, 매우중요한 특징)
print("벡터 결과:", result)

# 다. 벡터화 연산: 벡터와 벡터 연산
list_value= [90,80,70]
list_value2= [10,20,30]
result = list_value + list_value2 # [90, 80, 70, 10, 20, 30]
print(result)

vector_value = np.array(list_value)
vector_value2 = np.array(list_value2)
result = vector_value + vector_value2 # [100 100 100],요소간 연산
print(result)

# 라. 얕은 복사(주소값복사) 와 깊은 복사(실제값복사)
list_value= [90,80,70]
s = list_value[:]  # 파이썬의 슬라이싱은 깊은복사,   list(), .copy()
list_value[0]=900
print(list_value)
print(s)

list_value= [10,20,30]
vector_value = np.array(list_value)
s = vector_value[:] # 벡터의 슬라이싱은 얕은복사 ==> 성능 때문에
vector_value[0]=100
print(vector_value)
print(s)

# 벡터의 깊은복사(실제값복사) 방법
list_value= [10,20,30]
vector_value = np.array(list_value)
# new_vector_value = vector_value.copy()
new_vector_value = np.copy(vector_value)
vector_value[0]= 100

print(vector_value) # [100  20  30]
print(new_vector_value) # [10 20 30] , 깊은복사이기 때문에 수정 안됨.

* 출력 화면

 

 1차원 배열 생성_Vector3_array 함수3_속성

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)
   나. 속성
     print(dir(변수))


'''
import numpy as np

# 1. 벡터 생성
list_value= [10,20,30]
vector_value = np.array(list_value)
print("vector_value:", vector_value, type(vector_value)) # [10 20 30] <class 'numpy.ndarray'>

print("벡터의 차원크기:", vector_value.ndim) # 1
print("벡터의 형상(모양):", vector_value.shape) # (3,)  # 매우 중요하다.
print("벡터의 요소갯수:", vector_value.size) # 3
print("벡터의 요소타입:", vector_value.dtype) # int32

# print(dir(np))
# print(dir(vector_value))
'''
['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', 
'__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', 
'__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__class_getitem__', 
'__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', 
'__dir__', '__divmod__', '__dlpack__', '__dlpack_device__', '__doc__', '__eq__', '__float__', 
'__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', 
'__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', 
'__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', 
'__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', 
'__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', 
'__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', 
'__sub__', '__subclasshook__', '__truediv__', '__xor__', 


'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 
'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 
'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 
'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 
'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 
'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 
'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']
'''

* 출력 화면

 

 

 1차원 배열 생성_Vector4_랜덤 함수

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)
   나. 랜덤함수
      np.random.random() : [0.0  1.0) 범위값 반환
      np.random.random(size) : [0.0  1.0) 범위값에서 size만큼 반환
      np.random.rand()    : 0~1사이의 균등분포에서 반환, 뽑힐 확률 동일
      np.random.randn()    : 정규분포에서 반환, 평균이 0이고 표준편차 1 ==> N(0,1)
      np.random.randint(low, high=None) : high 미지정시 범위:  [0 low) ==> 0<= 값 <low
      np.random.randint(low, high) :   [low high) ==> low<= 값 <high


'''
import numpy as np
# 랜덤값 고정 ==> seed 고정
# np.random.seed(1234)

arr = np.random.random() # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("random() 함수:", arr, type(arr))  # <class 'float'>

arr = np.random.random(3) # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("random(size) 함수:", arr, type(arr)) # <class 'numpy.ndarray'>

arr = np.random.rand() # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("rand() 함수:", arr, type(arr)) # <class 'float'>

arr = np.random.rand(5) # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("rand(size) 함수:", arr, type(arr)) # <class 'numpy.ndarray'>

arr = np.random.randn() # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("randn() 함수:", arr, type(arr)) # <class 'float'>

arr = np.random.randn(7) # [0.0  1.0) ==> 범위   0.0 <=    <1.0
print("randn(size) 함수:", arr, type(arr)) # <class 'numpy.ndarray'>

arr = np.random.randint(5) # 0 ~ 4까지의 랜덤값 반환
print("randint(low) 함수:", arr, type(arr)) # <class 'int'>

arr = np.random.randint(1,3) # 1<=  < 3까지의 랜덤값 반환
print("randint(low, high) 함수:", arr, type(arr)) # <class 'int'>

arr = np.random.choice(["A","B","C"])
print("choice()", arr)

list_value=[5,2,56,67]
np.random.shuffle(list_value)
print(list_value)


# print(dir(np.random))
'''
['BitGenerator', 'Generator', 'MT19937', 'PCG64', 'PCG64DXSM', 'Philox', 
'RandomState', 'SFC64', 'SeedSequence', '__RandomState_ctor', '__all__', '__builtins__', 
'__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', 
'__spec__', '_bounded_integers', '_common', '_generator', '_mt19937', '_pcg64', 
'_philox', '_pickle', '_sfc64', 

'beta', 'binomial', 'bit_generator', 'bytes', 'chisquare', 'choice', 
'default_rng', 'dirichlet', 'exponential', 'f', 'gamma', 'geometric', 
'get_state', 'gumbel', 'hypergeometric', 'laplace', 'logistic', 'lognormal', 
'logseries', 'mtrand', 'multinomial', 'multivariate_normal', 'negative_binomial', 
'noncentral_chisquare', 'noncentral_f', 'normal', 'pareto', 'permutation', 
'poisson', 'power', 'rand', 'randint', 'randn', 'random', 'random_integers', 
'random_sample', 'ranf', 'rayleigh', 'sample', 'seed', 
'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 
'standard_gamma', 'standard_normal', 'standard_t', 'test', 'triangular', 
'uniform', 'vonmises', 'wald', 'weibull', 'zipf']
'''

* 출력 화면

 

 1차원 배열 생성_Vector5_zeros_ones

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)
   나. 랜덤함수
      np.random.random() : [0.0  1.0) 범위값 반환
      np.random.random(size) : [0.0  1.0) 범위값에서 size만큼 반환
      np.random.rand()    : 0~1사이의 균등분포에서 반환, 뽑힐 확률 동일
      np.random.randn()    : 정규분포에서 반환, 평균이 0이고 표준편차 1 ==> N(0,1)
      np.random.randint(low, high=None) : high 미지정시 범위:  [0 low) ==> 0<= 값 <low
      np.random.randint(low, high) :   [low high) ==> low<= 값 <high

   다. np.zeros(size, dtype=타입)
      ==> 모든 요소를  0.0 으로 채운 벡터 반환

   라. np.ones(size, dtype=타입)
      ==> 모든 요소를  1.0 으로 채운 벡터 반환
   마. np.empty(size, dtype=타입)
      ==> 임의의 값으로 초기화 됨, 값이 작으면 대부분이 1로 설정됨.
          임의의 값 초기화 확인 위해서는 size 늘려서 실습한다.

   마. np.full(size, 값, , dtype=타입)
      ==> 지정된 값으로 초기화 됨
'''
import numpy as np

arr = np.zeros(5)
print("zeros(size):" , arr) # [0. 0. 0. 0. 0.]
arr = np.zeros(5, dtype=int) # dtype=np.int32
print("zeros(size, dtype=int):" , arr) # [0 0 0 0 0]

arr = np.ones(5)
print("ones(size):" , arr) # [1. 1. 1. 1. 1.]
arr = np.ones(5, dtype=int) # dtype=np.int32
print("ones(size, dtype=int):" , arr) # [1 1 1 1 1]

arr = np.empty(5)
print("empty(size):" , arr) #
arr = np.empty(5, dtype=int) # dtype=np.int32
print("empty(size, dtype=int):" , arr)

arr = np.full(4, 100, dtype=int) # dtype=np.int32
print("full(size, 값, , dtype=타입):" , arr) # [100 100 100 100]

* 출력 화면

 1차원 배열 생성_Vector6_arange 함수

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)
   나. 랜덤함수
      np.random.random() : [0.0  1.0) 범위값 반환
      np.random.random(size) : [0.0  1.0) 범위값에서 size만큼 반환
      np.random.rand()    : 0~1사이의 균등분포에서 반환, 뽑힐 확률 동일
      np.random.randn()    : 정규분포에서 반환, 평균이 0이고 표준편차 1 ==> N(0,1)
      np.random.randint(low, high=None) : high 미지정시 범위:  [0 low) ==> 0<= 값 <low
      np.random.randint(low, high) :   [low high) ==> low<= 값 <high

   다. np.zeros(size, dtype=타입)
      ==> 모든 요소를  0.0 으로 채운 벡터 반환

   라. np.ones(size, dtype=타입)
      ==> 모든 요소를  1.0 으로 채운 벡터 반환
   마. np.empty(size, dtype=타입)
      ==> 임의의 값으로 초기화 됨, 값이 작으면 대부분이 1로 설정됨.
          임의의 값 초기화 확인 위해서는 size 늘려서 실습한다.

   마. np.full(size, 값, , dtype=타입)
      ==> 지정된 값으로 초기화 됨

   바. np.arange([start],stop[,step], dtype=타입)
    ==> 파이썬의 range()함수 유사하다.
'''
import numpy as np

arr = np.arange(5) # np.arange(stop) ==> [0 5)범위의 벡터 반환
print("arange(stop):", arr) # [0 1 2 3 4]

arr = np.arange(1,5) # np.arange(start, stop) ==> [1 5)범위의 벡터 반환
print("arange(start, stop):", arr) # [1 2 3 4]

arr = np.arange(1,10,2) # np.arange(start, stop, step) ==> [1 10)범위의 2step 벡터 반환
print("arange(start, stop, step):", arr) # [1 3 5 7 9]

# 실수값 반환
arr = np.arange(5, dtype=np.float32) # np.arange(stop, dtype=타입) ==> [0 5)범위의 벡터 반환
print("arange(stop):", arr) # [0. 1. 2. 3. 4.]

arr = np.arange(5.)
print("arange(stop):", arr) # [0. 1. 2. 3. 4.]

* 출력 화면

 1차원 배열 생성_Vector7_linspace 함수

 

'''
   배열생성
   1차원 배열:  벡터(vector)
   가. np.array(리스트)
   나. 랜덤함수
      np.random.random() : [0.0  1.0) 범위값 반환
      np.random.random(size) : [0.0  1.0) 범위값에서 size만큼 반환
      np.random.rand()    : 0~1사이의 균등분포에서 반환, 뽑힐 확률 동일
      np.random.randn()    : 정규분포에서 반환, 평균이 0이고 표준편차 1 ==> N(0,1)
      np.random.randint(low, high=None) : high 미지정시 범위:  [0 low) ==> 0<= 값 <low
      np.random.randint(low, high) :   [low high) ==> low<= 값 <high

   다. np.zeros(size, dtype=타입)
      ==> 모든 요소를  0.0 으로 채운 벡터 반환

   라. np.ones(size, dtype=타입)
      ==> 모든 요소를  1.0 으로 채운 벡터 반환
   마. np.empty(size, dtype=타입)
      ==> 임의의 값으로 초기화 됨, 값이 작으면 대부분이 1로 설정됨.
          임의의 값 초기화 확인 위해서는 size 늘려서 실습한다.

   마. np.full(size, 값, , dtype=타입)
      ==> 지정된 값으로 초기화 됨

   바. np.arange([start],stop[,step], dtype=타입)
    ==> 파이썬의 range()함수 유사하다.

   사.  np.linspace(start, stop, size)
    ==> 시각화할때 많이 사용됨.
'''
import numpy as np

arr = np.linspace(1,10,10)
print("np.linspace(1,10,10):", arr) # [ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

arr = np.linspace(1,10,10,endpoint=False)
print("np.linspace(1,10,10):", arr) # [1.  1.9 2.8 3.7 4.6 5.5 6.4 7.3 8.2 9.1]

arr = np.linspace(0,1,11)
print("np.linspace(0,1,11):", arr) # [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]

* 출력 화면

 출처

 

 

+ 강의 교재

'AI Bootcamp > Numpy' 카테고리의 다른 글

[Numpy] 1일차_1차열 배열 추가 및 삭제  (0) 2022.04.19
[Numpy] 1일차_0차열 배열  (0) 2022.04.19

0차원 배열 

 

 

 스칼라 array 함수

 

'''
   배열생성
   0차원 배열:  스칼라
'''
import numpy as np
print("numpy 버전:", np.__version__) # numpy 버전: 1.22.3

# 1. 스칼라 생성
s = np.array(10)

print("값:", s) # 10
print("타입:", type(s)) # <class 'numpy.ndarray'>
print("차원:", s.ndim) # 0
print("형상(모양):", s.shape) # ()

print(dir(np))
'''
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 
'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 
'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 
'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 
'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'RAISE', 'RankWarning', 
'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 
'Tester', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 
'VisibleDeprecationWarning', 'WRAP', '_CopyMode', '_NoValue', '_UFUNC_API', '__NUMPY_SETUP__', 
'__all__', '__builtins__', '__cached__', '__config__', '__deprecated_attrs__', '__dir__', 
'__doc__', '__expired_functions__', '__file__', '__getattr__', '__git_version__', '__loader__', 
'__name__', '__package__', '__path__', '__spec__', '__version__', '_add_newdoc_ufunc', 
'_distributor_init', '_financial_names', '_from_dlpack', '_globals', '_mat', '_pytesttester', 
'_version', 

'abs', 'absolute', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 
'alen', 'all', 'allclose', 'alltrue', 'amax', 'amin', 'angle', 'any', 'append', 
'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 
'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 
'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 
'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 
'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 
'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'binary_repr', 'bincount', 
'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 
'bool8', 'bool_', 'broadcast', 'broadcast_arrays', 'broadcast_shapes', 'broadcast_to', 
'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'bytes0', 
'bytes_', 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'cfloat', 'char', 
'character', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 
'common_type', 'compare_chararrays', 'compat', 'complex128', 'complex64', 'complex_', 
'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 
'copysign', 'copyto', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 
'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 
'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 
'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 
'diff', 'digitize', 'disp', 'divide', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 
'e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 
'euler_gamma', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 
'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 
'flip', 'fliplr', 'flipud', 'float16', 'float32', 'float64', 'float_', 'float_power', 'floating', 
'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 
'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 
'fromregex', 'fromstring', 'full', 'full_like', 'gcd', 'generic', 'genfromtxt', 'geomspace', 
'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 
'geterrobj', 'gradient', 'greater', 'greater_equal', 'half', 'hamming', 'hanning', 'heaviside', 
'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 
'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 
'infty', 'inner', 'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'intc', 'integer', 
'interp', 'intersect1d', 'intp', 'invert', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 
'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 
'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 
'ix_', 'kaiser', 'kron', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 
'linalg', 'linspace', 'little_endian', 'load', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 
'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 
'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mask_indices', 'mat', 
'math', 'matmul', 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 
'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum', 'mintypecode', 
'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 
'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 
'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndim', 'ndindex', 
'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'numarray', 
'number', 'obj2sctype', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'os', 
'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'place', 'poly', 
'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 
'polyval', 'positive', 'power', 'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put', 
'put_along_axis', 'putmask', 'quantile', 'r_', 'rad2deg', 'radians', 'random', 'ravel', 
'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 
'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 
'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 
'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypes', 
'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 
'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'short', 
'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 
'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 
'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'sys', 'take', 
'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 
'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 
'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typecodes', 
'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 
'uintp', 'ulonglong', 'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 
'unwrap', 'use_hugepage', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 
'vsplit', 'vstack', 'warnings', 'where', 'who', 'zeros', 'zeros_like']
'''

* 출력 화면

 

 출처

 

 

+ 강의 교재

'AI Bootcamp > Numpy' 카테고리의 다른 글

[Numpy] 1일차_1차열 배열 추가 및 삭제  (0) 2022.04.19
[Numpy] 1일차_1차원 배열 생성  (0) 2022.04.19

설치

 

 

 Python 설치

 

1. python 설치 진행 - python 사이트 접속

https://www.python.org/

https://www.python.org/downloads/release/python-381/

 

Python Release Python 3.8.1

The official home of the Python Programming Language

www.python.org

 

 

2. python 3.8.1 Windows x86-64 executable installer 다운로드

 

3. python 설치 파일 다운로드 완료되면 실행

 

4. 아래 2가지 체크 후 Customize installation 마우스로 클릭 

- Install launcher for all users (recommended)

- Add Python 3.8 to PATH

5. Next 마우스로 클릭

6. Customize install location 변경 -> Install 버튼 마우스로 클릭

C:\Users\UserName\AppData\Local\Programs\Python\Python38
C:\Python38

7. Python 3.8.1 설치 진행중인 화면 

8. Python 3.8.1 설치 완료

9. 시스템 정보 → 고급 시스템 설정

★ 시스템 정보 단축키 : Windows Key + Pause Key 

10.  시스템 속성 → 고급 → 환경 변수(N)...

11. 환경 변수 → 사용자 변수 → 편집

12. 환경 변수 편집에서 아래 2개의 경로 확인

C:\Python38\Scripts\
C:\Python38\

13. Python 3.8.1 설치된 경로에 정상 설치 여부 확인

 

 PyCharm 설치 및 설정

 

0. Pycharm 설치

https://www.jetbrains.com/pycharm/

https://inpages.tistory.com/99

설치가 되어 있다는 가정하에 설정

1.  File → New Project...

 

2. Previously configured interpreter → [...] 마우스로 클릭

3. Add Python Interpreter → System Interpreter → [...] 마우스로 클릭 → C:\Python38\python.exe 경로 설정 → OK 버튼 마우스로 클릭 → OK 버튼 마우스로 클릭

1. Add Python Interpreter → System Interpreter
2. Add Python Interpreter → [...] 마우스로 클릭 
3. Select Python Interpreter → C:\Python38\python.exe 경로 설정 
4. Select Python Interpreter OK 버튼 마우스로 클릭 
5.  Add Python Interpreter  OK 버튼 마우스로 클릭

4. Location → 우측 폴더 모양 마우스로 클릭

5. Select Base Directory - 경로를 C:\pythonstudy로 설정 후 OK 버튼 마우스로 클릭

6. 프로젝트 명은 python으로 입력 후 Create 버튼 마우스로 클릭

7. 프로젝트 생성 완료

 

 출처

 

 

+ 강의 교재

java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

 

org.apache.catalina.startup.HostConfig deployDescriptor
심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생
java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

 

라이브러리 충돌로 인한 에러

 

 해결방법

 

1. [Project] - [Clean]

2. Tomcat v8.5 Server at localhost → Modules → 실행되고 있는 것 선택 후 Remove

3. Servers → Tomcat v8.5 Server at localhost 마우스로 우클릭 → Clean

4. 해당 Project 마우스로 우클릭 → [Maven] → Update Project... → 해당 프로젝트 체크 후 OK 버튼 마우스로 클릭

1. 서버 클린 : Servers > Tomcat > Clean & Clean Tomcat Work Directory
2. 프로젝트 클린 : Menu > Project > Clean
3. 메이븐 업데이트 : Project Explorer > 프로젝트 우클릭 > Maven > Update Project

 

 

4가지 방법 해봐도 안됨..

 

3월 21, 2022 4:19:32 오후 org.apache.catalina.startup.HostConfig deployDescriptor 심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생 java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생

at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Caused by: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@5b39f964]을(를) 시작하지 못했습니다.

at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
... 9 more

Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다.

at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747)
at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 13 more

 

3월 21, 2022 4:40:09 오후 org.apache.catalina.core.StandardContext listenerStop
심각: 클래스 [org.springframework.web.context.ContextLoaderListener]의 인스턴스인 리스너에게 contextDestroyed 이벤트를 전송하는 중 예외 발생 java.lang.IllegalStateException: java.io.FileNotFoundException: C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc16_@ExceptionHandler\WEB-INF\lib\aspectjrt-1.6.10.jar (지정된 경로를 찾을 수 없습니다)
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.getArchiveEntry
(AbstractSingleArchiveResourceSet.java:100)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.getResource
(AbstractArchiveResourceSet.java:257) at org.apache.catalina.webresources.StandardRoot.getResourceInternal(StandardRoot.java:280)
at org.apache.catalina.webresources.Cache.getResource(Cache.java:62)
at org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:215)
at org.apache.catalina.webresources.StandardRoot.getClassLoaderResource(StandardRoot.java:224)
at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2365)
at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:876)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1379)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1223)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:117)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4811)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:844)
at org.apache.catalina.startup.HostConfig.undeploy(HostConfig.java:1458)
at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1383)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1646)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1170)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren
(ContainerBase.java:1396)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren
(ContainerBase.java:1400)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1368)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException:
C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc16_@ExceptionHandler\WEB-INF\lib\aspectjrt-1.6.10.jar (지정된 경로를 찾을 수 없습니다)
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:226)
at java.util.zip.ZipFile.<init>(ZipFile.java:155)
at java.util.jar.JarFile.<init>(JarFile.java:167)
at java.util.jar.JarFile.<init>(JarFile.java:131)
at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:202)
at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:187)
at org.apache.catalina.webresources.AbstractArchiveResourceSet.openJarFile
(AbstractArchiveResourceSet.java:308)
at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.getArchiveEntry
(AbstractSingleArchiveResourceSet.java:96)
... 24 more

 

 

경고: 호스트 appBase 내의 docBase [C:\springstudy\apache-tomcat-8.5.73\webapps\spring16_mvc13_mybatis]이(가) 지정되었으나, 이는 무시될 것입니다. 3월 21, 2022 5:22:06 오후 org.apache.catalina.core.ContainerBase addChildInternal 심각: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@675b709e]을(를) 시작하지 못했습니다. at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다. at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 13 more 3월 21, 2022 5:22:06 오후 org.apache.catalina.startup.HostConfig deployDescriptor 심각: 배치 descriptor [C:\springstudy\apache-tomcat-8.5.73\conf\Catalina\localhost\app.xml]을(를) 배치하는 중 오류 발생 java.lang.IllegalStateException: 자식 컨테이너를 시작하는 중 오류 발생 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:757) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:673) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1881) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.catalina.LifecycleException: 구성요소 [org.apache.catalina.webresources.StandardRoot@675b709e]을(를) 시작하지 못했습니다. at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4880) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5018) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) ... 9 more Caused by: java.lang.IllegalArgumentException: 지정된 주요 리소스셋 [C:\springstudy\apache-tomcat-8.5.73\webapps\app]은(는) 유효하지 않습니다. at org.apache.catalina.webresources.StandardRoot.createMainResourceSet(StandardRoot.java:747) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:705) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 13 more
3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext listenerStart 심각: Context initialized 이벤트를 [org.springframework.web.context.ContextLoaderListener] 클래스의 인스턴스인 리스너에 전송하는 동안 예외 발생 org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/tx] Offending resource: ServletContext resource [/WEB-INF/spring/root-context.xml] at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:118) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:110) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:301) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1432) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1419) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:172) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:126) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:614) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:514) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4763) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5232) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1177) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1925) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext startInternal 심각: 하나 이상의 리스너들이 시작하지 못했습니다. 상세 내역은 적절한 컨테이너 로그 파일에서 찾을 수 있습니다. 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext startInternal 심각: 이전 오류들로 인해 컨텍스트 [/spring16_mvc13_mybatis]의 시작이 실패했습니다. 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.ApplicationContext log 정보: Closing Spring root WebApplicationContext INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Mon Mar 21 17:22:26 KST 2022]; root of context hierarchy 3월 21, 2022 5:22:32 오후 org.apache.catalina.core.StandardContext listenerStop 심각: 클래스 [org.springframework.web.context.ContextLoaderListener]의 인스턴스인 리스너에게 contextDestroyed 이벤트를 전송하는 중 예외 발생 java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:164) at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1034) at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009) at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:958) at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:583) at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:116) at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4811) at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5467) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:187) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:727) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:695) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1177) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1925) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)

 

 

 출처

 

https://zerowincoding.tistory.com/entry/%EC%9E%90%EC%8B%9D-%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88%EB%A5%BC-%EC%8B%9C%EC%9E%91%EC%A4%91-%EC%8B%A4%ED%8C%A8%ED%96%88%EC%8A%B5%EB%8B%88%EB%8B%A4

maven update

https://velog.io/@kchm0224/%EC%8A%A4%ED%94%84%EB%A7%81-%EA%B5%AC%EB%8F%99-%EC%98%A4%EB%A5%98-%ED%95%B4%EA%B2%B0

https://blog.studioego.info/3388

https://how-can-i.tistory.com/3

https://repacat.tistory.com/30

https://zelkun.tistory.com/entry/eclipse-javautilconcurrentExecutionException-orgapachecatalinaLifecycleException

+ 강의 교재

Server Tomcat v8.5 Server at localhost failed to start.

 

 

 해결방법

 

* Tomcat v8.5 Server at localhost → Server Options → Publish module contexts to separate XML files 체크 후 Ctrl + S (저장)

 

 

 

 출처

 

https://blog.naver.com/PostView.naver?blogId=starry_night1003&logNo=222134335543&parentCategoryNo=&categoryNo=7&viewDate=&isShowPopularPosts=true&from=search 

https://beagle-dev.tistory.com/76

+ 강의 교재

Port 8005 required by Tomcat v8.5 Server at localhost is already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).

 

 

간단한 코드 실행해보려 했는데, 바로 에러 발생

 

 해결 방법

 

1. CMD(명령 프롬프트)창 관리자 권한으로 실행 

Windows Key → CMD 검색 → 명령 프롬프트 앱 마우스로 우클릭 → 자세히 → 관리자 권한으로 실행

2. 

netstat -ano | findstr 8005

taskkill /F /pid ?????

netstat -ano | findstr 8005

 

 

 출처

 

https://devlimk1.tistory.com/151

+ 강의 교재

Spring Apache Tomcat Server 설정

 

Eclipse와 설정 방법이 비슷하다.

까먹어서 다시 정리해보자.

 

 Spring Apache Tomcat Server 설정

 

1.  STS3 실행 → Server 탭 → No servers are availavle. Click this link to create a new server... 마우스로 클릭

 

2. [New Server] → [Apache] → [Tomcat v8.5 Server] → Next 버튼 마우스로 클릭

3. [Tomcat installation directory] → Browse... 버튼 마우스로 클릭하여 apache-tomcat 8.5 저장된 경로 선택 

→ JRE: → Installed JREs... 버튼 클릭하여 설치한 jdk 버전 선택 → Finish 버튼 마우스로 클릭

4. Server 탭 → Tomcat v8.5 Server at localhost [Stopped, Republish] 마우스로 더블 클릭하여 실행

 

5. [Tomcat v8.5 Server at localhost] → [Server Locations] → Use Tomcat installation (takes control of Tomcat installation) 체크 → Deploy path:  → Browse... 버튼 클릭하여 apache-tomcat-8.5.xx\webapps 폴더 선택 후 Ctrl + s로 설정 저장

 

 출처

 

 

+ 강의 교재

 

해당 프로젝트 F5로 새로고침 진행해봐도 안되서 서버 삭제 후 새로 만듬

실습 5일차_AOP

 

 

 Spring AOP

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		UserService service = ctx.getBean("userService", UserService.class);
		System.out.println("반환값:"+ service.insert());

	}
}

MainClass2.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;

public class MainClass2 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		DeptService service = ctx.getBean("deptService", DeptService.class);
		System.out.println("반환값:"+ service.selectList());

	}
}

MainClass3.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;
import com.service.EmpService;

public class MainClass3 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		EmpService service = ctx.getBean("empService", EmpService.class);
		try {
		  service.update();
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

MainClass4.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;
import com.service.PersonService;

public class MainClass4 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		PersonService service = ctx.getBean("personService", PersonService.class);
		try {
		  String str = service.delete();
		  System.out.println("반환값:"+str);
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

 

DeptServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class DeptServiceAspect {

	@AfterReturning(pointcut = "execution(* selectList(..))", returning = "retVal")
	public void doAccessCheck(Object retVal) {
		System.out.println("DeptServiceAspect.AfterReturning.selectList");
		System.out.println("리턴값:" + retVal);
	}
}

EmpServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

//부가기능 처리: aspect
@Aspect
public class EmpServiceAspect {

	@AfterThrowing(pointcut = "execution(* update(..))", throwing = "ex")
	public void doRecoveryActions(Exception ex) {
		System.out.println("EmpServiceAspect.AfterThrowing" 
	     + ex.getMessage());
	}
}

PersonServiceAspect.java

package com.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

//부가기능 처리: aspect
@Aspect
public class PersonServiceAspect {
 
		@Around("execution(* delete(..))")
	    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
	        System.out.println("Before Advice");
	        Object retVal = pjp.proceed();
	        System.out.println("After Advice");
	        System.out.println("retVal:" + retVal);
	        return retVal;
	    }
}

UserServiceAspect.java

package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

//부가기능 처리: aspect
@Aspect
public class UserServiceAspect {
  //1. pointcut와 advice 분리
	@Pointcut("execution(* list(..))")// the pointcut expression
	private void anyOldTransfer() {}// the pointcut signature
	
	@Before("anyOldTransfer()")
    public void doAccessCheck(JoinPoint point) {
		System.out.println("point:" + point);
		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.list");
    }
	
	//2. pointcut와 advice 합치기
	@Before("execution(* insert*(..))")
    public void doAccessCheck2(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.insert");
    }
	
	@After("execution(* insert*(..))")
    public void doAccessCheck3(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.AfterAdvice.insert");
    }
}

 

DeptService.java

package com.service;
import java.util.Arrays;
import java.util.List;

//타겟 (target object) ==> 핵심기능
public class DeptService {

	public List<String> selectList(){
		System.out.println("핵심기능:DeptService.selectList");
		return Arrays.asList("AAA","BBB");
	}
}

EmpService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class EmpService {

	public void update() {
		int num = 10/2;
		System.out.println("핵심기능:EmpService.update");
	}
}

PersonService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class PersonService {

	public String delete() {
		int num = 10/0;
		System.out.println("핵심기능:PersonService.insert");
		return "Hello";
	}
}

UserService.java

package com.service;

//타겟 (target object) ==> 핵심기능
public class UserService {

	//pointcut
	public String list() {
		return "UserService.list";
	}

	public String insert() {
		System.out.println("핵심기능:UserService.insert");
		return "UserService.insert";
	}
	public String insert2() {
		return "UserService.insert2";
	}	
}

user.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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<aop:aspectj-autoproxy />
	<!-- 1. BeforeAdvice와 AfterAdvice 실습 -->
	<bean id="userService" class="com.service.UserService" />
	<bean id="userAspect" class="com.aspect.UserServiceAspect" />
	
	<!-- 2. AfterReturningAdvice 실습 -->
	<bean id="deptService" class="com.service.DeptService" />
	<bean id="deptAspect" class="com.aspect.DeptServiceAspect" />
	
	<!-- 3 AfterThrowingAdvice 실습 -->
	<bean id="empService" class="com.service.EmpService" />
	<bean id="empAspect" class="com.aspect.EmpServiceAspect" />
	
	<!-- 4 AroundAdvice 실습 -->
	<bean id="personService" class="com.service.PersonService" />
	<bean id="personAspect" class="com.aspect.PersonServiceAspect" />
</beans>

 

* aop 추가 방법

[Namespaces] → [Configure Namespaces] 팝업창 OK 버튼 마우스로 클릭

 

* 출력 화면 

MainClass 출력화면

 

MainClass2 출력화면

 

MainClass3 출력화면

 

MainClass4 출력화면

 

 Spring AOP Component_Scan

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		UserService service = ctx.getBean("userService", UserService.class);
		
		System.out.println(service.insert());
		//System.out.println(service.list());

	}
}

MainClass2.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.DeptService;
import com.service.UserService;

public class MainClass2 {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
				
		DeptService service2 = ctx.getBean("deptService", DeptService.class);
		System.out.println("반환값:" + service2.selectList());
		//System.out.println(service.list());
		
	}
}

MainClass3.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;

public class MainClass3 {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		EmpService service = ctx.getBean("empService", EmpService.class);
			
		try {
			service.update();
		} catch (Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
		
	}
}

MainClass4.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.EmpService;
import com.service.PersonService;

public class MainClass4 {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		PersonService service = ctx.getBean("personService", PersonService.class);
		try {
		  String str = service.delete();
		  System.out.println("반환값:"+str);
		}catch(Exception e) {
			System.out.println("error");
		}
		System.out.println("정상종료");
	}
}

 

DeptServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DeptServiceAspect {

	@AfterReturning(pointcut = "execution(* selectList(..))", returning = "retVal")
	public void doAccessCheck(Object retVal) {
		System.out.println("DeptServiceAspect.AfterReturning.selectList");
		System.out.println("리턴값:" + retVal);
	}
}

EmpServiceAspect.java

package com.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class EmpServiceAspect {

	@AfterThrowing(pointcut = "execution(* update(..))", throwing = "ex")
	public void doRecoveryActions(Exception ex) {
		System.out.println("EmpServiceAspect.AfterThrowing" 
	     + ex.getMessage());
	}
}

PersonServiceAspect.java

package com.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class PersonServiceAspect {
 
	 @Around("execution(* delete(..))")
	    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
	        System.out.println("Before Advice");
	        Object retVal = pjp.proceed();
	        System.out.println("After Advice");
	        System.out.println("retVal:" + retVal);
	        return retVal;
	    }
}

UserServiceAspect.java

package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//부가기능 처리: aspect
@Component
@Aspect
public class UserServiceAspect {
  //1. pointcut와 advice 분리
	@Pointcut("execution(* list(..))")// the pointcut expression
	private void anyOldTransfer() {}// the pointcut signature
	
	@Before("anyOldTransfer()")
    public void doAccessCheck(JoinPoint point) {
		System.out.println("point:" + point);
		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.list");
    }
	
	//2. pointcut와 advice 합치기
	@Before("execution(* insert*(..))")
    public void doAccessCheck2(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.BeforeAdvice.insert");
    }
	
	@After("execution(* insert*(..))")
    public void doAccessCheck3(JoinPoint point) {
//		System.out.println("point:" + point);
//		System.out.println("method명:" + point.getSignature().getName());
        System.out.println("UserServiceAspect.AfterAdvice.insert");
    }
}

 

DeptService.java

package com.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;

//타켓(target object) ==> 핵심기능
@Service
public class DeptService {
	public List<String> selectList(){
		System.out.println("핵심기능:DeptService.selectList");
		return Arrays.asList("AAA", "BBB");
	
	}
}

EmpService.java

package com.service;
import org.springframework.stereotype.Service;

//타켓(target object) ==> 핵심기능
@Service
public class EmpService {
	public void update() {
		int num = 10/2;
		System.out.println("핵심기능:EmpService.update");
	}
}

PersonService.java

package com.service;
import org.springframework.stereotype.Service;

// 타겟 (target object) ==> 핵심기능
@Service
public class PersonService {
	public String delete() {
		int num = 10/2;
		System.out.println("핵심기능:PersonSerivce.insert");
		return "Hello";
	}
}

UserService.java

package com.service;
import org.springframework.stereotype.Service;

// 타켓(target object) ==> 핵심기능
@Service
public class UserService {

	// pointcut
	public String list() {
		return "UserService.list";
	}
	
	public String insert() {
		return "UserService.insert";
	}
	
	public String insert2() {
		return "UserService.insert2";
	}
}

 

user.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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<aop:aspectj-autoproxy />
	<context:component-scan base-package="com.*"></context:component-scan>
</beans>

 

* 출력 화면 

MainClass 출력화면
MainClass2 출력화면
MainClass3 출력화면
MainClass4 출력화면

 

 출처

 

AOP : 

+ 강의 교재

 

실습 5일차_SpEL

 

https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/expressions.html

 

 Spring SpEL_Collection_Selection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
			
		ListPerson listPerson = ctx.getBean("list1", ListPerson.class); //System.out.println(list1);
		List<Person> list1 = listPerson.getList();
		System.out.println("1. 전체 데이터 출력");
		
		for (Person person : list1) {
			System.out.println(person);
		}
		
		ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class); //System.out.println(list1);
		List<Person> list2 = listPerson2.getList();
		System.out.println("2. SpEL 전체 데이터 출력");
		for (Person person : list2) {
			System.out.println(person);
		}
		
		ListPerson listPerson3 = ctx.getBean("list3", ListPerson.class); //System.out.println(list1);
		List<Person> list3 = listPerson3.getList();
		System.out.println("3. SpEL 특정 인덱스 데이터 출력");
		for (Person person : list3) {
			System.out.println(person);
		}
		
		ListPerson listPerson4 = ctx.getBean("list4", ListPerson.class); //System.out.println(list1);
		List<Person> list4 = listPerson4.getList();
		System.out.println("4. SpEL 조건 데이터 출력");
		for (Person person : list4) {
			System.out.println(person);
		}
		
		ListPerson listPerson5 = ctx.getBean("list5", ListPerson.class); //System.out.println(list1);
		List<Person> list5 = listPerson5.getList();
		System.out.println("5. SpEL 멀티 조건 데이터 출력");
		for (Person person : list5) {
			System.out.println(person);
		}
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {

	List<Person> list;

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + "]";
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
		<bean id="p1" class="com.dto.Person" p:username="고길동" p:age="30" p:married="true" p:weight="50" />
		<bean id="p2" class="com.dto.Person" p:username="신길동" p:age="40" p:married="false" p:weight="60" />
		<bean id="p3" class="com.dto.Person" p:username="홍길동" p:age="10" p:married="false" p:weight="70" />
		<bean id="p4" class="com.dto.Person" p:username="이길동" p:age="25" p:married="true" p:weight="60" />
	</util:list>
	
	<bean id="list1" class="com.dto.ListPerson">
		<property name="list" ref="personList" />
	</bean>
	
	<!-- SpEL -->
	<bean id="list2" class="com.dto.ListPerson">
		<property name="list" value="#{personList}"/>
	</bean> 
	
	<!-- SpEL -->
	<bean id="list3" class="com.dto.ListPerson">
		<property name="list" value="#{personList[1]}"/>
	</bean> 
	
	<!-- SpEL -->
	<!-- 행선택(selection) 문법 ===> 참조값.?[조건식] -->
	<bean id="list4" class="com.dto.ListPerson">
		<property name="list" value="#{personList.?[age > 25]}"/>
	</bean> 
	
	<!-- SpEL -->
	<!-- 행선택(selection) 문법 ===> 참조값.?[조건식 and 조건식 or 조건식] -->
	<bean id="list5" class="com.dto.ListPerson">
		<property name="list" value="#{personList.?[age > 25 and married == true]}"/>
	</bean>

</beans>

* 출력 화면 

 

 Spring SpEL_Collection_Projection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		ListPerson listPerson1 = ctx.getBean("list1", ListPerson.class);
	    List<String> usernameList = listPerson1.getUsernameList();
	    System.out.println("1. username 프라퍼티 전체 출력");
	    for (String name : usernameList) {
			System.out.println(name);
		}
	
	    ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class);
	    List<Integer> ageList = listPerson2.getAgeList();
	    System.out.println("2. age 프라퍼티 전체 출력");
	    for (int age : ageList) {
			System.out.println(age);
		}
	
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {

	// selection
	List<Person> list;
	
	// projection
	List<String> usernameList;
	List<Integer> ageList;
	
	public List<String> getUsernameList() {
		return usernameList;
	}

	public void setUsernameList(List<String> usernameList) {
		this.usernameList = usernameList;
	}

	public List<Integer> getAgeList() {
		return ageList;
	}

	public void setAgeList(List<Integer> ageList) {
		this.ageList = ageList;
	}

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + "]";
	}
	
}

Person.java

package com.dto;

public class Person {

	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
}

user.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"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
	   <bean id="p1" class="com.dto.Person" p:username="홍길동" p:age="30" p:married="true" p:weight="78.6" />
	   <bean id="p2" class="com.dto.Person" p:username="고길동" p:age="40" p:married="false" p:weight="100.2" />
	   <bean id="p3" class="com.dto.Person" p:username="신길동" p:age="10" p:married="false" p:weight="56.2" />
	   <bean id="p4" class="com.dto.Person" p:username="이길동" p:age="23" p:married="true" p:weight="75.6" />
	</util:list>
	
	 <!-- 
	   selection 문법:  참조변수.?[조건식] , 참조변수.?[조건식 and 조건식 or 조건식] 
	 -->
	 
	 <!-- 
	     projection 문법:  참조변수.![property]  
	 -->
	 <bean id="list1" class="com.dto.ListPerson">
	   <property name="usernameList" value="#{personList.![username]}" />
	 </bean>
	 
	 <bean id="list2" class="com.dto.ListPerson">
	   <property name="ageList" value="#{personList.![age]}" />
	 </bean>
</beans>

* 출력 화면 

 

 Spring SpEL_Collection_Selection & Projection

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.ListPerson;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		ListPerson listPerson1 = ctx.getBean("list1", ListPerson.class);
	    List<String> usernameList = listPerson1.getUsernameList();
	    System.out.println("1. username 프라퍼티 조건 출력");
	    for (String name : usernameList) {
			System.out.println(name);
		}
	
	    ListPerson listPerson2 = ctx.getBean("list2", ListPerson.class);
	    List<Integer> ageList = listPerson2.getAgeList();
	    System.out.println("2. age 프라퍼티 조건 출력");
	    for (int age : ageList) {
			System.out.println(age);
		}
	
	}
}

ListPerson.java

package com.dto;
import java.util.List;

public class ListPerson {
	
	// selection
	List<Person> list;
	
	// projection
	List<String> usernameList;
	List<Integer> ageList;
	
	public List<String> getUsernameList() {
		return usernameList;
	}

	public void setUsernameList(List<String> usernameList) {
		this.usernameList = usernameList;
	}

	public List<Integer> getAgeList() {
		return ageList;
	}

	public void setAgeList(List<Integer> ageList) {
		this.ageList = ageList;
	}

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}

	@Override
	public String toString() {
		return "ListPerson [list=" + list + ", usernameList=" + usernameList + ", ageList=" + ageList + "]";
	}

}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<util:list id="personList">
	   <bean id="p1" class="com.dto.Person" p:username="고길동" p:age="30" p:married="true" p:weight="78.6" />
	   <bean id="p2" class="com.dto.Person" p:username="신길동" p:age="40" p:married="false" p:weight="100.2" />
	   <bean id="p3" class="com.dto.Person" p:username="홍길동" p:age="10" p:married="false" p:weight="56.2" />
	   <bean id="p4" class="com.dto.Person" p:username="이길동" p:age="23" p:married="true" p:weight="75.6" />
	</util:list>
	
	 <!-- 
	   selection 문법:  참조변수.?[조건식] , 참조변수.?[조건식 and 조건식 or 조건식] 
	 -->
	 
	 <!-- 
	     projection 문법:  참조변수.![property]  
	 -->
	 
	 <!-- 
	     selection 및 projection 조합
	         ==> 참조변수.?[조건식].![property]
	  -->
	 <bean id="list1" class="com.dto.ListPerson">
	   <property name="usernameList" value="#{personList.?[age > 25].![username]}" />
	 </bean>
	 
	 <bean id="list2" class="com.dto.ListPerson">
	   <property name="ageList" value="#{personList.?[married==true].![age]}" />
	 </bean>
</beans>

 

* 출력 화면 

 

 출처

 

 

+ 강의 교재

 

실습 5일차_SpEL

 

SpEL - Spring Expression Language
Spring Expression Language는 보통 SpEL로 표기하며 구두로는 Spring EL이라고 지칭한다.
SpEL은 보통 객체를 조회하고 조작하는 기능을 제공하여 Unified EL과 유사하지만
Method 호출, 문자열 템플릿 기능 등의 여러가지 추가 기능을 제공하는 표현식 언어이다.
Spring 3.0부터 지원된다.

 

 Spring SpEL 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean isMarried;
	double weight;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isMarried() {
		return isMarried;
	}
	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ "]";
	}
}

user.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="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{'신길동'}" />
		<property name="age" value="#{20+10}" />
		<property name="married" value="#{10>4}" />
		<property name="weight" value="#{'75.75'}" />
	</bean>
	
</beans>

 

* 출력 화면 

 

 Spring SpEL_ref 

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
	}
}

Cat.java

package com.dto;

public class Cat {

	String name;
	int age;
	String sex;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}

}

Person.java

package com.dto;

public class Person {

	String username;
	int age;
	boolean isMarried;
	double weight;
	
	Cat cat;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isMarried() {
		return isMarried;
	}

	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}

	public double getWeight() {
		return weight;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", isMarried=" + isMarried + ", weight=" + weight
				+ ", cat=" + cat + "]";
	}
	
}

user.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="c1" class="com.dto.Cat">
	  <property name="name" value="나비" />
	  <property name="age" value="2" />
	  <property name="sex" value="암컷" />
	</bean>

	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="57.25" />
		<property name="cat" ref="c1" />  <!-- ref 이전 -->		
	</bean>

    <bean id="p2" class="com.dto.Person">
		<property name="username" value="홍길동" />
		<property name="age" value="30" />
		<property name="married" value="true" />
		<property name="weight" value="77.77" />
		<property name="cat"  value="#{c1}"/>  <!-- SpEL -->  		
	</bean>
</beans>

* 출력 화면 

 

 Spring SpEL_property

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
}

user.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="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person">
		<property name="username" value="#{p1.username}" />
		<property name="age" value="#{p1.age+10}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
</beans>

* 출력 화면 

 

 Spring SpEL_method

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		Person p1 = ctx.getBean("p1", Person.class);
		System.out.println(p1);
		
		Person p2 = ctx.getBean("p2", Person.class);
		System.out.println(p2);
		
		Person p4 = ctx.getBean("p4", Person.class);
		System.out.println(p4);
		
	}
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int age;
	boolean married;
	double weight;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}

	public boolean getMarried() {
		return married;
	}
	
	public void setMarried(boolean married) {
		married = married;
	}
	
	public double getWeight() {
		return weight;
	}
	
	public void setWeight(double weight) {
		this.weight = weight;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + ", married=" + married + ", weight=" + weight + "]";
	}
	
	// 필요에 의해서 추가된 메서드
	public String getName() {
		return "GOKilDong";

	}
	
	public String getName2() {
		//return "GOKilDong";
		return null;
	}
	
	// static 메서드
	public static String getName3() {
		return "Park";
	}
	
}

user.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="p1" class="com.dto.Person"> <!-- 필요에 의해서 추가된 메서드에도 접근할 수 있다. SpEL로 메서드 호출 가능 -->
		<property name="username" value="#{p1.getName()}" />
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<!-- SpEL --> <!-- 다른  bean에 있는 property 값 접근할 수 있음 -->
	<bean id="p2" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName().toUpperCase()}" />
		<property name="age" value="#{p1.age}" />
		<property name="married" value="#{p1.married}" />
		<property name="weight" value="#{p1.weight}" />
	</bean>
	
	<bean id="p3" class="com.dto.Person"> 
		<property name="username" value="#{p1.getName2()?.toUpperCase()}" /><!-- 에러 방지? -->
		<property name="age" value="20" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
	<bean id="p4" class="com.dto.Person"> <!-- static 메서드 호출 방법 -->
		<property name="username" value="#{T(com.dto.Person).getName3()}" /><!-- .java가 아니기에 pakage명까지 넣어줘야 함 -->
		<property name="age" value="#{T(java.lang.Math).random()+1 * 10.0}" />
		<property name="married" value="true" />
		<property name="weight" value="45.45" />
	</bean>
	
</beans>

* 출력 화면 

 

 출처

 

SpEL : https://atoz-develop.tistory.com/entry/Spring-SpEL-Spring-Expression-Language

+ 강의 교재

 

+ Recent posts