NOW OR NEVER

[Spring] Spring boot로 Spring project 생성 본문

Back-End/JAVA

[Spring] Spring boot로 Spring project 생성

LAURA 2022. 6. 2. 14:38
반응형
  • sts 다운로드 : https://spring.io/tools

  • 내장 서버 포함되어 있어 따로 서버 설정하지 않아도 됨

  • file - new - spring Starter project

    • type : maven일 경우 필요한 jar를 알아서 다운로드 해줌

    • package : web application할 거면 war

    • next - available 칸에 작성하고 검색하여 뭐가 필요한지 선택하면 선택한 것을 기준으로 환경설정 해줌(dependency)

      • controller, dao, vo 등 모든 클래스들은 기본적으로 생성되는 package의 하위에 작성해야 자동으로 스캔됨
      • 어노테이션
      • @ResponseBody: 데이터로 응답
    • @SpringBootApplication이 정의된 파일에서 run as 누른 후 spring boot app 누르기 - 웹 주소에 localhost:8080/controller파일내 @RequestMapping로 정의한 값 치기 - @ResponseBody 밑에 작성한 함수 작동

Spring Project 만드는 과정

  • \1. pom.xml : maven 설정하는 파일

    • dependencies 태그 안에 작성

    • jsp를 사용하기 위한 메이븐 설정

       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       </dependency>
      
       <dependency>
       <groupId>org.apache.tomcat.embed</groupId>
       <artifactId>tomcat-embed-jasper</artifactId>
       <scope>provided</scope>
       </dependency>
  • \2. src/main/resources - application.properties에 아래 코드 작성

     spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
     spring.datasource.url=jdbc:oracle:thin:@localhost:192.168.35.217:1521:XE
     spring.datasource.data-username=c##sist
     spring.datasource.data-password=sist
    
      #server.port=8088  
      #server.session.timeout=36000
    
      #view를 찾을 위치  
      spring.mvc.view.prefix=/WEB-INF/views/
    
      #view의 확장자  
      spring.mvc.view.suffix=.jsp
  • \3. vo 작성(vo package)

    • setter, getter 생성
    • 매개 변수 없는 생성자 생성
  • \4. mybatis 설정파일, 매핑파일작성(db package)

    • mybatis 설정 파일 생성 : xml 파일 생성 후 xml 파일 source에 아래 코드 작성

          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE configuration
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-config.dtd">
          <configuration>
          <environments default="development">
          <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
              <property name="driver" value="${driver}"/>
              <property name="url" value="${url}"/>
              <property name="username" value="${username}"/>
              <property name="password" value="${password}"/>
            </dataSource>
          </environment>
          </environments>
          <mappers>
          <mapper resource="org/mybatis/example/BlogMapper.xml"/>
          </mappers>
          </configuration>
  • db.properties 파일 생성 - driver, url, username, password 각각에 application properties에 작성한 값과 동일하게 작성

  • mapping 파일 생성 - xml 파일 생성 후 아래 코드 작성

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="org.mybatis.example.BlogMapper">
    <select id="selectBlog" resultType="Blog">
      select * from Blog where id = #{id}
    </select>
    </mapper>
  • \5. DBManger 클래스 생성

    public static SqlSessionFactory sqlSessionFactory;
    
    static {
       try {
           String resource = "com/example/demo/db/sqlMapConfig.xml"; // sql환경변수 파일 주소 입력
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       } catch (Exception e) {
           System.out.println("예외발생: " + e.getMessage());
       }
    }
    
    public static List<DeptVO> listDept() {
       // mapping 파일에 있는 sql문 실행시키기 위해
       List<DeptVO> list = null;
    
       SqlSession session = sqlSessionFactory.openSession();
       list = session.selectList("dept.findAll");
       session.close();
       return list;
    }
  • \6. dao 작성

    • @Repository 코드 작성으로 dao 파일임을 인식시킴
  • \7. controller 작성

  • \8. viewPage 작성

lombok

  • lombok 설치할 때 sts 파일 경로에 한글이 들어 있으면 sts가 실행이 되지 않는 에러 발생할 수 있음. 이경우 sts 파일 경로를 영어로만 구성되게 옯기고 lombok을 다시 설치해야 함
  • lombok 설치 : https://mvnrepository.com/artifact/org.projectlombok/lombok 에서 최신 버전으로 jar 설치 - 설치한 jar 파일 C드라이브에 옮기기(단, spring 프로젝트 워크페이스도 c 드라이브에 위치해야 함)
  • lombok 실행(cmd) : cd\ -> java - jar lombok
  • lombok 실행 exe : specify location - sts 설치 위치로 가서 SpringToolSuite4.exe 선택 - install
  • 어노테이션
  • setter, getter 등을 @을 활용해 간단하게 만들 수 있다.
  • @setter : 세터 생성
  • @getter : 게터 생성
  • @AllArgsConstructor :매개변수 있는 생성자 생성
  • @NOArgsConstructor :매개변수 없는 생성자 생성
  • @ToString
  • @Data : setter, getter, constructor, tostring 생성해줌

file upload

Tips

  • 설치 dependencies : my batis framework, oracle driver, spring web, lombok
  • 기능 추가시 : mapper - DBmanager - dao - controller - vo-- - jsp 파일 순으로 작성
  • failed to configure a datasource: 'url' attribute is not specified and no embedded datasource could be configured. 에러 해결 : pom.xml의 오른쪽 클릭- maven - upeate project - 안되는 프로젝트 체크 - ok

'Back-End > JAVA' 카테고리의 다른 글

[Spring] JqGrid / AOP  (0) 2022.06.22
[Spring] Jquery  (0) 2022.06.17
[Spring] 스프링 MVC 기초  (0) 2022.05.27
[JAVA] JDBC(Java DataBase Connection Programming)  (0) 2022.04.15
[JAVA] Network Programming  (0) 2022.04.14
Comments