jongviet

June 25, 2021 - Spring 개인 필기 본문

Spring legacy

June 25, 2021 - Spring 개인 필기

jongviet 2021. 6. 25. 16:58

*6월25일

-스프링 관련 기본 개념에 대해 필기한 내용을 포스팅 해보자.

 

 

*스프링 프로젝트 복제 방법

-프로젝트 copy&paste 후 -> pom.xml name을 '새프로젝트명'으로 변경-> Spring\workspace\새프로젝트명\.settings의 org.eclipse.wst.common.component(톰캣 관련) 파일의 <wb-module deploy-name="새프로젝트명"> 수정 ->  target폴더의 pom.properties + pom.xml 모두 '새프로젝트명'으로 바뀐지 확인 + spring 프로젝트 폴더의 .project도 파일도 바뀐지 확인

-만약 에러 발생시 pom.xml 속성 -> maven -> update proejct

 

*스프링 관련 기초

-Spring tool suite 3 / on Eclipse 4.16버전

-Spring-tool-suite-3.9.15.RELEASE-e4.16.0-win32-x86_64

-pom.xml은 maven 관리 툴; 라이브러리 버전 등 세팅, core + utils

-spring project는 pom.xml을 가장 먼저 읽음

-root-context.xml에는 DB 관련 사항이 들어가있음

-web.xml의 ContextLoaderListener가 전체 프로젝트 로드

-Spring에서는 생성자 따로 안만듬.....

->Spring이 알아서 VO 객체의 이름을 그대로 매핑시켜서, ctrl에 req.getParameter를 알아서 해줌..... 따라서 생성자 만들 필요가 없는 것...

->결과적으로 getter & setter만 만들면됨.

-DispatcherServlet가 스프링에서 50% 이상 일을 함, 컨트롤타워 느낌  -> request를 받은 후, 어느 view로 보내서 처리할 것인가에 대한 일을 함 -> servlet-context.xml에 주로 설정사항 담음

-원래는 oracle.properties의 DB 비밀번호 암호화 해야함 -> 암호화는 각자 알아서 해보면됨!

-스프링 경로 지정시, 프로젝트 완전히 밖으로 나갈 때 '\\'로하고, 프로젝트 내에 있을 때는 '/'로 씀; 파일첨부 DIR과 같은 느낌

-스프링에는 간단하게 root가 3개라고 생각하면됨(java = src(jsp), webapp = webContent(jsp), resources = config, mappers, mybatisConfig 위치)

 

Spring roots

 

*자바 클래스 하나 하나를 bean이라고 함. -> beans라는 건 클래스의 집합(즉, application을 구성하는 요소들임)

->spring core가 확인한 모든 bean들을 instance화 해서 메모리상에 올려놓는 (new 처리) 세팅을 해줌.....

->사용하면 spring이 알아서 타이밍 잡아주고, 사용안하면 내려줌

->spring이 이러한 객체들을 모두 제어함, 이게 바로 제어의 역전(IOC)

->sqlSession 사용 시 clearcache는 필수

 

*스프링 로직

-scanning 될 수 있게 다 @componet 등록 -> web.xml -> root & servlet context를 모두 읽고 인스턴스화 해놓음! -> dispatcher servlet -> controller 찾고 -> request를 받아서 로직 실행 -> 백단 처리 -> view resolver에 던져서 -> jsp

-component화 시킨다는게 읽을 수 있게 만든다는 것이고, 이걸 annotation으로 함. @Controller, @Repository, @Service 등

-bean에 등록하여 사용 시, spring framework 코어가 작동할때 자동으로 다 인스턴스화 시켜서 메모리에 올림,,, component scan에 등록 시 바로는 아니고 내가 호출을 했을 때 인스턴스화 시켜서 메모리에 올림(리스팅 한다는 것!);
->즉 무조건 필수, 사용자 작업 흐름에 따른 선택적 필수로 구분함.

 

*기 완성된 프로젝트 활용하여 spring 다시 세팅 하는 순서

-pom.xml 세팅 -> web.xml -> root-context.xml -> servlet-context.xml -> resources/bootstrap -> src/text/java의 com.myweb.ctrl의 dummyTest f2키로 라이브러리 추가 -> src/main/resources 추가 -> src/main/java 추가

 

*Spring에서는 mapper에서 param type에 풀네임이 아닌 'String, int' 만쓰면 됨; Spring mapper 변수 선언 방법은 하기와 같음

 

    <sql id="bc">

        from tbl_member where email = #{email}

    </sql>

    <select id="check" parameterType="String"  resultType="int">

        SELECT count(email) as cnt <include  refid="bc"/>

    </select>

 

*서버를 키지 않고 memberDummyTest로 테스트 가능!!

-DAO까지만 만들고 DB에 service 단 가기전에 테스트 먼저 함!

-junit 이용해서 서버 켜지 않고 DB에 연결하여 테스트 해볼 수 있음. 실제 DB에 데이터 삽입 가능.

-실무에서 테스트할때는 insert, delete 따로 진행함;

-DAO, service 각 레이어 별로 테스트 가능

 

*dispatcher servlet안에, 수많은 RequestMapping이 있다는 것 인지

-dispatcherServlet/controllers/requestMappings와 같은 계층 구조임.

-return "home";  //리턴값은 viewResolver가 처리해줌~

-jsp에서 request -> dispatcherServlet/controllers/RequestMapping(nextSt) -> return -> return값.jsp로 이동

 

 

*주요파일

 

1)root-context.xml(DB, SQL, mybatis, VO)

-설정한 bean들은 어디에서든 당겨 쓸 수 있게 됨! 인스턴스화 되어 스프링 구동시 바로 메모리에 올라간다는 것~

-domain은 db를 거친다기보다 우리만의 저장소 개념이기에 bean으로 따로 등록하지 않음(VO classes)

-패키지들을 모두 검색해서 등록함, 즉 DB와 연결될 가능성이 있는걸 위주로 등록

 

    <context:component-scan  base-package="com.myweb.persistence"/>

    <context:component-scan  base-package="com.myweb.orm"/>

    <context:component-scan  base-package="com.myweb.service"/>

    <context:component-scan  base-package="com.myweb.handler"/>

 

-DB 관련 정보가 담긴 config/oracle.properties를 매핑

 

    <context:property-placeholder  location="classpath:/config/*.properties"/>

 

-데이터의 경로, 즉 DB 정보; config에서 끌어옴;

 

        <bean id="dataSource"  class="com.zaxxer.hikari.HikariDataSource"  destroy-method="close">

        <property name="driverClassName"  value="${db.driverClassName}"></property>

        <property name="jdbcUrl"  value="${db.jdbcUrl}"></property>

        <property name="username"  value="${db.username}"></property>

        <property name="password"  value="${db.password}"></property>

 

-SqlSessionFactoryBuilder

-bean의 id값들이 메모리에 올라가면 다 클래스타입으로 바뀌면서 SqlSession, DataSource식으로 대문자로 바뀜!

 

    <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">  

        <property name="dataSource"  ref="dataSource"></property>

        <property name="configLocation"  value="classpath:/MybatisConfig.xml"></property> //VO들의 Alias 연결

        <property name="mapperLocations"  value="classpath:mappers/**/*Mapper.xml"></property>  //SQL문 집합 

    </bean>

 

-생성자 인자값; 반드시 clearCache 해야함.

 

    <bean id="sqlSession"  class="org.mybatis.spring.SqlSessionTemplate"  destroy-method="clearCache">

        <constructor-arg  name="sqlSessionFactory"  ref="sqlSessionFactory"></constructor-arg>  

    </bean>

 

-Transaction으로 JSP pooling 한계점 보완 가능

 

    <bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource"  ref="dataSource"></property>

    </bean>

 

-annotation으로 관리하겠다는 선언 개념

 

    <tx:annotation-driven/>

    <task:annotation-driven/>

 

2)servlet-context.xml(Controller)

-어느 위치값에서도 바로 ${webappRoot}/resources에 쉽게 접속할 수 있게 mapping 해둠; 

'../'없이 header에서 바로 /resources/bootstrap....으로 import 할 수 있는 이유임

-파일 저장도 이런식으로 경로 잡아서 처리할 수 있음!

 

  <resources mapping="/resources/**"  location="/resources/" />

 

  <link rel="stylesheet"  href="/resources/bootstrap/css/bootstrap.min.css">

  <script  src="/resources/bootstrap/js/jquery-3.6.0.min.js"></script>

  <script  src="/resources/bootstrap/js/popper.min.js"></script>

  <script  src="/resources/bootstrap/js/bootstrap.min.js"></script>

 

-jsp 파일 분기 처리용~

 

<beans:bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <beans:property name="prefix"  value="/WEB-INF/views/" /> //접두사와 접미사만 적고, 안에 들어갈 값을 ctrl에서 return으로 던짐;

        <beans:property name="suffix"  value=".jsp" />

    </beans:bean>

 

-request 처리용 패키지를 검색해서 등록, 일반적으로 ctrl 하나임

 

    <context:component-scan  base-package="com.myweb.ctrl" />

 

3)pom.xml

-각종 라이브 러리 dependencies 잡아주는 곳!!

-spring, aspectJ, logging, @Inject, servlet, DB, test, utils 등등등~

 

4)web.xml

-encoding 처리, DispatcherServlet, root-context.xml, servlet-context.xml 경로 지정

-ContextLoaderListener가 전체 프로젝트  로드 하는 역할을 함

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener

        </listener-class>

    </listener>

 

 

Comments