Spring-Boot入門注意事項

層級目錄

常用註解說明

控制器主體 Controller

  • @RestController
    對整個controller裏面的所有方法都以json格式輸出,不需要在對方法的返回結果做Json轉換。適合應用於 RESTful API 開發工程。

  • @Controller
    最常用的控制器註解。與@RestController 的區別在於@Controller下的方法返回值有方法註解控制可以跳轉頁面,也可以做Ajax請求返回Json數據。

  • @RequestMapping
    用來處理地址映射請求(URL路由信息,頁面跳轉)。

@Controller
public class UserController {

}

控制器方法

  • @RequestMapping("/user/list") //頁面跳轉
@RequestMapping("/user/list") //接口請求地址 http://127.0.0.1:8080/user/list
public String toList() {
    return "/user/userlist";//頁面跳轉:跳轉到用戶列表頁 /user/userlist.html
}
  • @ResponseBody //Ajax 響應

其中Ajax請求地址爲:/user.lists,POST 方式請求
@RequestBody HashMap<String, Object> param 將頁面參數直接封裝到Map 計劃中

@ResponseBody
@RequestMapping(value = "/user.lists", method = RequestMethod.POST)
@LoggerManage(description = "用戶列表接口")
public ResponseData getList(@RequestBody HashMap<String, Object> param){
    int pageNo = Convert.getInteger(null == param.get("pageNo") ? "0" : param.get("pageNo"));
    int pageSize = Convert.getInteger(null == param.get("pageSize") ? "0" : param.get("pageSize"));
return userService.queryUser(param, pageNo, pageSize);
}

實體類 Entity

@Entity //註解這是個實體類
@Table(name=“t_user”) //設置數據庫中表名字,不配置時,表名默認與實體類名字一致

@Entity  
@Table(name="t_user")
public class User {

}

@Id //ID 主鍵
@GeneratedValue //ID 主鍵自增長

@Id
@GeneratedValue
private Long id;

@Column //字段特性、名稱等標識

//主鍵表ID
@Column(nullable = false)
private String mid;

//創建時間
@Column(nullable = false)
private Timestamp createdTime;

@Transient //標識該字段並非數據庫字段映射

@Transient//不映射成列的字段
private String lN;//登錄時傳輸的登錄名

資源引入

@Autowired
private UserService userService;

@Autowired
private EntityManager entityManager;

啓動類

  • @SpringBootApplication
  • @EnableScheduling//啓用定時任務

啓動類

啓動類必須存放於項目的根目錄,且整個項目有且只有一個啓動類(只能有一個帶Main方法的類)

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

PS:當項目中存在多個Main方法是,程序會報找不到啓動類的錯誤。
image

配置定時任務

  • 在啓動類中添加類註解 @EnableScheduling
@SpringBootApplication
@EnableScheduling//啓用定時任務
public class SpbootApplication {
    public static void main(String[] args) {
    	SpringApplication.run(SpbootApplication.class, args);
	}
}
  • 在定時任務實現類中添加時間參數配置
@Scheduled(fixedDelay = 5000)//上一次執行完畢時間點之後5秒再執行
//@Scheduled(fixedRate = 5000)//上一次開始執行時間點之後5秒再執行
//@Scheduled(cron = "*/5 * * * * ?")// cron 表達式
private void doWork() {

}

pom.xml 配置文件引入 springboot starter 包。
PS:多個定時任務默認是竄行的方式運行,定時任務並行需要在 resources 目錄下添加 applicationContext.xml 配置文件,並在根目錄下添加配置文件解析器 XmlImportingConfiguration.java ,文件內容具體如下:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:task="http://www.springframework.org/schema/task"
    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.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">


    <!-- Enables the Spring Task @Scheduled programming model -->
    <task:executor id="executor" pool-size="5" />
    <task:scheduler id="scheduler" pool-size="2" />
    <task:annotation-driven executor="executor" scheduler="scheduler" />


</beans>

XmlImportingConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext.xml")
public class XmlImportingConfiguration {

}

Logback 日誌配置

Spring Boot 支持多種日誌輸出組件,這裏介紹Logback的配置方式

  • pom.xml 引入依賴包
<dependency>
	<groupId>com.googlecode.log4jdbc</groupId>
	<artifactId>log4jdbc</artifactId>
	<version>1.2</version>
</dependency>
  • logback.xml 配置(resources根目錄)
<?xml version="1.0"?>
<configuration>
	<!-- 控制檯輸出: %m輸出的信息,%p日誌級別,%t線程名,%d日期,%c類的全名,,,, -->
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d %p (%file:%line\)- %m%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<appender name="baselog"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>log/base.log</File>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>log/base.log.%d.%i</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy
				class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<!-- or whenever the file size reaches 64 MB -->
				<maxFileSize>64 MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder>
			<pattern>
				%d %p (%file:%line\)- %m%n
			</pattern>
			<!-- 設置字符集 -->
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<!-- show parameters for hibernate sql 專爲 Hibernate 定製 -->
	<!-- <logger name="org.hibernate.SQL" level="DEBUG">
		<appender-ref ref="baselog" />
		<appender-ref ref="STDOUT" />
	</logger>
	<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE">
		<appender-ref ref="baselog" />
		<appender-ref ref="STDOUT" />
	</logger> -->
	<root level="info">
		<appender-ref ref="STDOUT" />
	</root>
	<logger name="com.izhonghong.spboot" level="DEBUG">
		<appender-ref ref="baselog" />
	</logger>
</configuration>
  • 代碼調用
logger.debug("login failed log ");

動態SQL

  • 引入實體管理器 EntityManager
@Autowired
private EntityManager entityManager;
  • 通過動態SQL獲取查詢結果集(其中,sql 爲動態拼裝後的sql語句)
List<Object[]> list = entityManager.createNativeQuery(sql).getResultList();

URI命名規則

  • 頁面跳轉
@RequestMapping("/users")
public String toUsers() {
    return "/user/userlist";
}
  • Ajax 方法請求
url : "/user.lists"

Thymeleaf 獲取Java 後端變量

獲取 session、request參數

  • 頁面頭部引用
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
  • 調用示例
<span th:if="${session.login_user !=null}">
    <span th:text="${session.login_user.loginName}"></span>
</span>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章