三、Springboot學習3-自定義配置-2018-11-13
1. 自定義配置
1.1 application.properties
com.test.title=測試標題
com.test.description=測試內容
1.2 自定義配置類
@Component public class TestProperties { @Value("${com.boot.title}") private String title; @Value("${com.boot.description}") private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
2. 配置日誌輸出地址和輸出級別
# 配置log輸出地址和輸出級別,path為本機的log地址,logging.level 後面可以根據包路徑配置不同資源的log級別 logging.path=/user/local/log logging.level.com.boot.springboot=DEBUG logging.level.org.springframework.web=INFO logging.level.org.hibernate=ERROR
3. 資料庫操作
spring data jpa使用
3.1 新增資料庫操作相關依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
3.2 新增配置檔案
# mysql資料庫操作相關配置 spring.datasource.url=jdbc:mysql://localhost:3306/hzf?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
注意:上面如果不加serverTimezone=GMT%2B8會報錯,說明設定時區有問題,GMT%2B8代表是東八區
3.3 新增實體類
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
3.4 構建dao
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
}
4. 呼叫測試
5. 上面涉及到的註解:
serialVersionUID作用:Java的序列化機制是通過判斷類的serialVersionUID來驗證版本一致性的。在進行反序列化時,JVM會把傳來的位元組流中的serialVersionUID與本地相應實體類的serialVersionUID進行比較,如果相同就認為是一致的,可以進行反序列化,否則就會出現序列化版本不一致的異常,即是InvalidCastException。
nullable=false:欄位儲存時必須有值,傳Null去save會報錯,