1. 程式人生 > >快速開發框架SpringBoot-學習日記(三)

快速開發框架SpringBoot-學習日記(三)

第2章 Spring Boot重要用法

Spring Boot中使用JSP頁面

步驟:

  1. 在src/main下建立webapp目錄
  2. 將webapp目錄指定的web資源目錄
    在這裡插入圖片描述
  3. 匯入JSP引擎內建Tomcat的jasper
    <!--Spring Boot內嵌的Tomcat對JSP的解析包 jasper-->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    

Spring Boot中使用MyBatis

步驟:

  1. 匯入依賴
        <!--mybatis與Spring Boot整合依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--資料來源Druid依賴-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--MySQL驅動依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
  1. 修改配置檔案
mybatis:
  # 註冊mybatis中實體類的別名
  type-aliases-package: com.bjpowernode.bean
  # 註冊對映檔案
  mapper-locations: classpath:com/bjpowernode/dao/*.xml

# 註冊資料來源
spring:
  datasource:
    # 指定資料來源型別為Druid
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///test?useUnicode=true&amp;characterEncoding=utf8
    username: root
    password: 111

  1. 在Dao介面上新增@Mapper註解
@Mapper
public interface StudentDao {
    void insertStudent(Student student);
}


Spring Boot中使用事務

在Service實現類的方法上新增@Transactional註解

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao dao;

    // 採用Spring預設的事務提交方式:發生執行時異常回滾,發生受查異常提交
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStudent(Student student) throws Exception {
        dao.insertStudent(student);
        // int i = 3 / 0;
        if (true) {
            throw new Exception("發生受查異常");
        }
        dao.insertStudent(student);
    }
}

在啟動類上新增@EnableTransactionManagement註解,開啟事務

@EnableTransactionManagement   // 開啟事務
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Spring Boot對日誌的支援

logback日誌技術簡介

Spring Boot預設使用logback日誌技術。Logback是由log4j創始人設計的又一個開源日誌元件,其效能要優於log4j,是log4j的替代者

logback在Spring Boot中的用法

logback在Spring Boot中具有兩種使用方式:

在主配置檔案中配置

# logback日誌控制
logging:
  # 指定日誌顯示的位置及格式
  pattern:
    console: logs-%level %msg%n

  level:
    root: warn    # 減少專案啟動時的日誌輸出
    com.bjpowernode.dao: debug    # 顯示指定dao包中類的執行日誌

在專門的檔案中配置

在src/main/resources下定義一個檔名為***logback.xml***的檔案。注意,存放路徑及檔名稱是不能改的。