4월, 2020의 게시물 표시

2020.04.27 TIL 스프링 - Spring Form Tag 사용하기

Spring의 form 태그는 이렇게 prefix를 붙이고 modelAttribute를 추가하여 사용한다. <form:form modelAttribute="student">   <form:input path="name">    // 자동으로 student모델의 getName()의 값이 초기 값으로 세팅되고, 이후에 submit을 하면 setName()이 호출된다. 언제나 case 유의할 것! 처음에 모델을 포함해서 HTML을 렌더링 해주는 controller는 아래와 같이 사용한다. ``` @RequestMapping("/showForm") public String showForm(Model theModel) { Student theStudent = new Student(); theModel.addAttribute("student", theStudent); theModel.addAttribute("theCountryOptions", countryOptions); return "student-form"; } ``` HTML 코드는 이러하고 ``` <form:form action="processForm" modelAttribute="student"> Student first name: <form:input path="firstName"/><br> Student last name: <form:input path="lastName"/><br> <form:select path="country"> <form:options items="${theCountryOptions}"/> </for...

2020.04.25 TIL 스프링 - XML 없이 Configuration 하기

## Configuration 클래스 작성 1. Create java class with @Configuration, @ComponentScan annotation @Configuration @ComponentScan(PACKAGE_NAME) public class MyConfig {} 2. Load Config class context at main file. main { AnnotationConfigApplicationContext context =   new AnnotationConfigApplicationContext(MyConfig.class); } ## Bean도 SpringContainer Config안에서 만들기 1. Config Class에서 @Bean annotation으로 바로 Bean을 주입할 수 있다. - 사전에 필요한 사항은 Bean 클래스가 구현할 인터페이스, Bean 클래스이다. @Configuration public class MyConfig() {   @Bean   public Something something() {     // 이 때 MySomething이 Bean으로 동작할 클래스로, Something을 구현하고 존재하고 있어야 함.     return new MySomething();   }   @Bean   public Another another() {     // 이 때 MyAnother Bean은 something을 inject 받는 Bean이다.     return new MyAnother(something());  //   } } ## Full Code ``` Main public class SwimJavaConfigDemoApp { public static void main(Stri...

2020.04.24 TIL 스프링 - Bean Scope Detail with Annotation

Bean은 특별한 지정 값이 없으면 언제나 싱글톤으로 만들어진다. https://everupgrade.blogspot.com/2020/04/20200408-bean-lifecycle-annotation-bean.html 그런데 이 설정을 굳이 xml이 아닌 Bean Class에서 편하게 할 수 있다. ``` @Component @Scope( singleton(default) or prototype(매번 새로운 객체 생성) or global(용어는 확실치않음. flask g처럼 동작 등 ) public class Bean... (대충 bean 클래스) ``` init, destroy hook도 마찬가지이다. ``` @Component public class Bean... (대충 bean 클래스)     @PostConstruct   public String initMethod() {..대충 bean 함수}   @PreDestroy   public String destroyMethod() {..대충 bean 함수} ``` 주의사항 prototype은 PreDestroy Annotation이 동작하지 않는다. 다른 Scope들은 모두 관리가 되는데 prototype은 스프링 컨테이너가 생성까지만 관여하고 destroy는 관여하지 않는다. 만약 prototype bean에 destroy 훅을 달고 싶으면 Bean이 DisposableBean interface를 구현하고 해당 인터페이스가 제공하는 destroy() 함수를 구현해야한다고 한다. 참고소스:   destroy-protoscope-bean-with-custom-processor.zip

2020.04.22 TIL 스프링 - AutoWiring(2), Qualifier

Bean Inject하는 방법은 3가지가 있고 아래와 같다. 1. Constructor Injection @Component public class NewCoach implements Coach {         private FortuneService fs;     @Autowired public NewCoach(@Qualifier("sadFortuneService") FortuneService fortuneService) {}; @Override public String getDailyWorkout() { // TODO Auto-generated method stub return null; } 2. Setter Injection @Component public class NewCoach implements Coach {         private FortuneService fs; @Autowired public String setFortuneService(FortuneService fs) {                 this.fs = fs; } 3. Field Injection @Component public class NewCoach implements Coach {         @Autowired         @Qualifier("happyFortuneService")         private FortuneService fs; Private 필드에 @Autowired를 붙여서 자동으로 Bean을 주입하고 사용하는 방식은 혼자 자바, 스프링 공부하는 내내 사용했던 문법인데 ...

2020.04.15 파이썬 - Shelve

파이썬 Built-in에 이런 모듈이 있는것을 처음 알았다. import shelve class CustomClass: def __init__ ( self , value): self .value = value def __repr__ ( self ): return f'<class: { self .__class__. __name__ } >' with shelve.open( 'test.db' ) as f: f[ 'my_int' ] = 100 f[ 'my_float' ] = 100.555 f[ 'my_str' ] = 'hello world!' f[ 'my_dict' ] = dict ( hello = 'world' ) f[ 'my_custom_class' ] = CustomClass( 'MyCustomClass' ) with shelve.open( 'test.db' ) as f: print (f[ 'my_int' ]) print (f[ 'my_float' ]) print (f[ 'my_str' ]) print (f[ 'my_dict' ]) print (f[ 'my_custom_class' ]) print (f[ 'my_custom_class' ].value) $ 100 $ 100.555 $ hello world! $ {'hello': 'world'} $ <class: CustomClass> $ MyCustomClass 이렇게 파이썬 객체들 중 picklable 한 객체들은 모두 파일에 저장해둘 수 있고, 불러올 때도 모두 깔끔히 ...

2020.04.14 처음부터, 스프링 - AutoWiring

@Autowired가 붙어있는 field가 있다면 자동으로 Component로 등록해 둔 클래스들 중에서 그 클래스를 찾은 뒤 Inject 시켜준다. 만약 Component로 등록 된 클래스가 하나라면 그 클래스만 무조건 Inject하게 된다. 클래스가 여러 개인 경우는 아직 안 배웠는데 적절히 Config 해줄 수 있는 듯 하다. @Autowired까지 써보니까 이제 DI가 어떤 부분이 크게 다른지 느낌이 조금은 온다. 파이썬, 플라스크 같으면 Class를 선언하고, 해당 클래스를 초기화 할 때 혹은 초기화 한 뒤 필드 값을 set하는 방식을 주로 사용할 것이다. 반면에 Spring은 Bean을 미리 초기화, 조립해서 만든 뒤에 실제 코드 실행부로 넘겨준다. Spring의 Bean은 파이썬에서 모델과 비슷하게 이해할 수 있을 것 같다. 이 방식의 장점은 매 번 필드값을 수동으로 설정하지 않더라도 쉽게 값을 set/get할 수 있다는 것과 모델의 생성 책임을 스프링이 져준다는 것인 것 같다.

2020.04.09 처음부터, 스프링 - Bean의 LifeCycle, Annotation으로 Bean 만들기

<Bean의 속성, 간단하게> Spring에서 생성하는 Bean은 기본적으로 싱글톤으로 동작한다. 만약 Bean을 싱글톤이 아닌 다른 방식으로 생성하고 싶으면 scope를 수정해주면 된다. scope에 사용할 수 있는 value는 singleton(기본), prototype(매번 새로운 객체가 생성됨) 이 있고 그 외에 HTTP request에 binding 하거나 HTTP 세션에 globally하게 반영할 수도 있다. (마치 flask의 g처럼) 그리고 Bean에는 init-method, destroy-method를 통해 hook도 등록이 가능하다. 객체의 생성과 종료 시기에 불려지는 함수이다. 주의할 것은 scope이 prototype이라면 bean은 destroy 훅이 동작하지 않는다. prototype의 bean에 destroy 훅을 걸고 싶다면, 새로운 인터페이스와 클래스를 만들고 Bean 클래스에서 해당 인터페이스를 구현하고 블라블라 하는 방법이 있는데 이거는 필요할 때 찾아보면 될 것 같다. <Annotation을 이용한 Bean 사용> 복잡하게 XML에 미리 모든 Bean을 써놓지 않고, 클래스에 Annotation을 주는 것만으로 해당 클래스가 Bean으로 동작하게 할 수 있다. XML에 설정할 것은 딱 하나이다. component를 스캔할 base-directory 지정하는 것. base-directory와 그 하위 폴더들까지 모두 탐색하며 컴포넌트 Annotation이 붙은 클래스를 찾고 그들을 모두 Bean으로 사용한다. 코드 예시를 보면, 아래처럼 @Component만 주면 tennicCoach가 자동으로 bean id가 되고 @Component("MyTennisCoach") 처럼 ID를 직접 명시할 수도 있다. @Component public class TennisCoach implements Coach { @Override public St...

2020.04.08 처음부터, 스프링 - DI

DI, Dependency Injection 1. Define the dependency interface and class. 2. Create a constructor in class for injections. (일단은 xml로 bean을 관리하는 방식만 배운 상태이다.) 먼저 XML에 모델(Bean)을 선언한다. 모델에서 사용하고자 하는 다른 클래스(혹은 다른 모델)가 있다면, 모델의 생성자에 다른 클래스를 추가한다. 그러면 모델을 초기화할 때 그 모델의 생성자에 추가해 둔 다른 클래스의 메소드를 사용할 수 있게 된다. 강의에서는 이해를 돕기 위해 dependency=helper라는 문구가 자주 나왔다. 거창하게 번역하면 의존성 주입인데, 앱에서 모델을 만들어서 사용하는 것이 아니고 Spring Container가 만든 채로 모델을 전달하는 방식이라고 생각하면 될 것 같다. 파이썬으로 치면 class A의 생성자가 class B의 메소드를 사용하기 위해, A의 생성자에 class B를 인자로 전달해서 실행하는 방식과 같다. 확실히 특이하긴 한데 아직까지 크게 효용성이 느껴지지는 않는다.