1. 程式人生 > 實用技巧 >Arrays.sort()自定義排序

Arrays.sort()自定義排序

SpringBoot

1.springboot入門

在該入門案例中,沒有任何配置,就可以實現一個SpringMVC專案

1.匯入依賴

<parent>
	<groupid>org.apringframework.boot<l groupid>
	<artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</ version>
</parent>
<!--        
<groupId>com.itheima</groupId>
<artifactId>heima-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
-->       
<properties>
    <java.version>1.8</java.version>
</properties>
        
<dependencies>
	<dependency>
        <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2.建立啟動引導類

package com.itheima ;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootapplication;
/**
* spring boot工程都有一個啟動引導類,這是工程的入口類
*並在引導類上新增@SpringBootApplication
*自動掃描所在包及其子包
*/
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
	SpringApplication.run(Application.class,args);
    }
}

3.建立處理器Controller,訪問即可

package com.itheima.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {   
	@GetMapping("hello")
	public String hello(){	
        return "Hello, Spring Boot!";
	}
}

2.SpringBoot的配置

2.1Java程式碼方式配置

2.1.1@Value的方式注入基本屬性

java配置主要靠java類和一些註解,比較常用的註解有:

  • @Configuration:宣告一個類作為配置類,代替xml檔案
  • @Bean:宣告在方法上,將方法的返回值加入Bean容器,代替標籤
  • @Value:屬性注入
  • @PropertSource:指定外部屬性檔案

我們接下來用java配置來嘗試實現連線池配置:

1.在pom.xml檔案中新增Druid連線池依賴如下

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.6</version>
</dependency>

2.建立jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc,url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=000000

3.建立配置類

@Configuration
@PropertSource("classpath:jdbc.properties")
public class JdbcConfig {
	@Value("${jdbc.ur1}")
    String url;
	@Value("${jdbc.driverclassName} ")
    String driverClassName;
	@Value("${jdbc.username}")
    String username;
	@Value("S{jdbc.passwor d}")
    String password;
	@Bean
	public Datasource datasource(){
		DruidDatasource datasource = new DruidDataSource(); 	 
        datasource.setDriverClassName(driverClassName);
        datasource.setUrl(ur1) ;
        datasource.setUsername(username);
        datasource.setPassword(password);
        return datasource;
	}
}

2.1.2@ConfigurationProperties物件屬性注入

目標:能夠使用@ConfigurationProperties實現Spring Boot配置檔案配置項讀取和應用

分析:
需求∶將配置檔案中的配置項讀取到一個物件中;
實現∶可以使用Spring Boot提供的註解@ConfigurationProperties,該註解可以將Spring Boot的配置檔案(預設必須為application。properties或application。yml)中的配置項讀取到一個物件中。

實現步驟︰
1.建立配置項類]dbcProperties類,在該類名上面新增@ConfigurationProperties ;

/**
*ConfigurationProperties 從applicatior配置檔案中讀取配置項
*prefix表示配置項的字首(如:jdbc.username中的jdbc)
*配置項類中的類變數名必須要與字首之後的配置項名稱保持鬆散繫結(相同)
*/
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private string url;
    private string driverClassName;
    private string username;
    private string password;
    //生成getter和setter方法
}

@ConfigurationProperties報紅,還需要新增依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
    <!--不傳遞依賴-->
	<optional>true</optional>
</dependency>

2.將jdbc.properties修改名稱為application.properties ;
3.將JdbcProperties物件注入到JdbcConfig ;

package com.itheima.config
@Configuration
//@PropertSource("classpath:jdbc.properties")
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
/**	@Value("${jdbc.ur1}")
    String url;
	@Value("${jdbc.driverclassName} ")
    String driverClassName;
	@Value("${jdbc.username}")
    String username;
	@Value("S{jdbc.passwor d}")
    String password;
*/    
	@Bean
	public Datasource datasource(JdbcProperties jdbcProperties){
		DruidDatasource datasource = new DruidDataSource(); 	 
        datasource.setDriverClassName(jdbcProperties.getDriverClassName());
        datasource.setUrl(jdbcProperties.getUrl()) ;
        datasource.setUsername(jdbcProperties.getUsername());
        datasource.setPassword(jdbcProperties.getPassword());
        return dataSource;
	}
}

4.測試

2.1.3更優雅的注入

事實上,如果一段屬性只有一個Bean需要使用,我們無需將其注入到一個類(JdbcProperties,將該類上的所有註解去掉)中。而是直接在需要的地方宣告即可;再次修改JdbcConfig類為如下程式碼:

@Configuration
public class Jdbcconfig {
    @Bean
    //宣告要注入的屬性字首,Spring Boot會自動把相關屬性通過set方法注入到Datasource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

我們直接把@ConfigurationProperties(prefix = "jdbc")宣告在需要使用的@Bean 的方法上,然後SpringBoot就會自動呼叫這個Bean(此處是DataSource)的set方法,然後完成注入。使用的前提是:該類必須有對應屬性的set方法!

2.2.yml檔案配置

目標:可以將多個yml檔案在application.yml檔案中配置啟用

分析:
yaml與properties配置檔案除了展示形式不相同以外,其它功能和作用都是一樣的;在專案中原路的讀取方式不需要改變。

yml配置檔案的特徵∶
1.樹狀層級結構展示配置項;
2.配置項之間如果有關係的話需要分行空兩格;
3.配置項如果有值的話,那麼需要在:之後空一格再寫配置項值;將application.properties配置檔案修改為application.yml的話:

jdbc:
  driverclassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/springboot_test
  username: root
  password: root
#啟用配置檔案;需要指定其它的配置檔名稱
spring:
  profiles:
    active: abc,def

2 )多個yml配置檔案;在spring boot中是被允許的。這些配置檔案的名稱必須為application-***.yml(如:application-abc.yml),並且這些配置檔案必須要在application.yml配置檔案中啟用之後才可以使用。
3 )如果properties和yml配置檔案同時存在在spring boot專案中﹔那麼這兩類配置檔案都有效。在兩個配置檔案中如果存在同名的配置項的話會以properties檔案的為主。

3.lombok應用

目標:使用lombok的註解實現pojo類的簡化

分析:
編寫資料庫表對應的實體類;一般情況下需要編寫get/set/toString等這些方法會讓實體類看起來比較臃腫。可以使用lombok外掛對實體類進行簡化。
lombok是一個外掛工具類包;提供了一些註解@Data、@Getter等這些註解去簡化實體類中的構造方法、get/set等方法的編寫。

步驟:

1.在IDEA中安裝lombok外掛;

2.新增lombok對應的依賴到專案pom.xml檔案

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

3.改造實體類使用lombok註解

import lombok.Data;
import java.util.Date;
//在編譯階段會根據註解自動生成對應的方法; data包含get/set/hashCode/equals/toStzing等方法
@Data
public class User {
    private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String note;
    private Date created;
    private Date updated;
}

然後可以在Bean上使用:
@Data:自動提供getter和setter、hashCode、equals、toString等方法 @Getter:自動提供getter方法
@Setter:自動提供setter方法
@Slf4j:自動在bean中提供log變數,其實用的是slf4j的日誌功能。
例如:在javabean上加@Data,那麼就可以省去getter和setter等方法的編寫,lombok外掛會自動生成。

4.SpringBoot整合SpringMVC攔截器

目標:可以在Spring Boot專案中配置自定義SpringMVC攔截器分析:
1.編寫攔截器(實現Handlerlnterceptor ) ;
2.編寫配置類實現WebMvcConfigurer,在該類中新增各種元件;

@Configuration
public class Mvcconfig implements WebMvcConfigurer {
    //註冊攔截器
    @Bean
    public MyInterceptor myInterceptor() {
    	return new MyInterceptor();
    }
    //新增攔截器到spring mvc攔截器鏈
    @Override
    public void addInterceptors(InterceptorRegistry registry){
   		registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
	}
}

3.測試

5.SpringBoot整合-事務和連線池

目標:配置Spring Boot自帶預設的hikari資料庫連線池和使用@Transactional註解進行事務配置

分析:
事務配置
1.新增事務相關的啟動器依賴,mysql相關依賴;

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysq1-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>

2.編寫業務類UserService使用事務註解@Transactional

資料庫連線池hikari配置
1.只需要在application配置檔案中指定資料庫相關引數

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    ur1: jdbc:mysql://127.0.0.1:3306/springboot_test
    username: root
    password: root

6.SpringBoot整合-Mybatis

目標∶配置Mybatis在Spring Boot工程中的整合包,設定mybatis的實體類別名,輸出執行sql語句配置項分析:
1.新增啟動器依賴;

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>

2.配置Mybatis :實體類別名包,日誌,對映檔案等;

mybatis:
  #實體類別名包路徑
  type-aliases-package: com.itheima.pojo
  #對映檔案路徑
  # mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdoutImpl

3.配置@MapperScan

可以在介面上配置@Mapper,但這種方法不推薦。

在啟動類上配置

//掃描mybatis所有的業務介面
@MapperScan("com.dtf.mapper")

7.SpringBoot整合-通用Mapper

目標︰配置通用Mapper元件到Spring Boot專案中並使用Mapper介面

分析:
通用Mapper:可以實現自動拼接sql語句;所有的mapper都不需要編寫任何方法也就是不用編寫sql語句。可以提高開發效率。

1.新增啟動器依賴;

<!--通用mapper -->
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

2.改造UserMapper繼承Mapper ;

public interface UserMapper extends Mapper<User> {
    
}

3.修改啟動引導類Application中的Mapper掃描註解;

//尤其注意,匯入tk.mybatis.spring.annotation.MapperScan包
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan("com.dtf.mapper")

4.修改User實體類新增jpa註解;

@Table(name = "tb_user")
public class User {
    @Id
    //主鍵回填
    @Keysql (useGeneratedKeys = true)
    private Long id;
    @Column (name = "user_name")
    //user_name --> userName
    private String userName;
    private String password;
    private Integer age;
    private Date updated;
}

5.UserService實現業務功能;

8.SpringBoot整合-Junit

目標:在Spring Boot專案中使用unit進行單元測試UserService的方法

分析:
1.新增啟動器依賴spring-boot-starter-test ;

<dependency>
	<groupId>org-springframework.boot<lgroupId>
	<artifactId>spring-boot-starter-test</artifactId>
</dependency>

2.編寫測試類

@RunWith(springRunner.class)
@SpringBootTest
public class UserserviceTest {
    @Test
}

小貼士:在類名上按住shift+ctrl+T就可快速建立測試類

9.SpringBoot整合-redis

目標∶在Spring Boot專案中使用Junit測試RedisTemplate的使用

分析 :
1.新增啟動器依賴;spring-boot-starter-data-redis

<dependency>
	<groupId>org-springframework.boot<lgroupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置application.yml中修改redis的連線引數;( redis需要啟動)

spring:
  redis:
    host: localhost
    port: 6379

3.編寫測試類應用RedisTemplate操作redis中的5種資料型別( string/hash/list/set/sorted set )

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
	@Autowired
	private RedisTemplate redisTemplate;
	@Test
    public void test (){
        
        // String字串
        // redisTemplate.opsForValue().set("str", "heima");
        redisTemplate.boundvalueOps(key:"str" ).set("heima");
        System.out.println("str = " + redisTemplate.opsForValue().get("str"));

        // hash 雜湊
        redisTemplate.boundHashOps("h_key").put("name","heima");
        redisTemplate.boundHashOps("h key").put("age",13);
        //獲取所有域
        Set set = redisTemplate.boundHashOps("h_key").keys();
        System.out.println ("hash雜湊的所有域:" + set);
        //獲取所有值
        List list = redisTemplate.boundHashOps("h _key").values();
        System.out.println ("hash雜湊的所有域" + list);

        //list列表
        redisTemplate.boundListOps("1_key").leftPush("c");
        redisTemplate.boundListOps("l_key").leftPush("b");
        redisTemplate.boundListOps("1_key").leftPush("a");
        //獲取全部元素
    	list = redisTemplate.boundListOps("1_key" ).range(0,-1);
        System.out.println("list列表中的所有元素:" +list);

    	// set集合
    	redisTemplate.boundSetOps("s_key").add("a","b","c");
        set = redisTemplate.boundSetOps("s_key" ).members();
        System.out.println("set集合中的所有元素:" + set);
        
    	// sorted set有序集合
    	redisTemplate.boundzsetOps("z_key").add("a",30);
        redisTemplate.boundzsetOps("z_key").add("b",20);
        redisTemplate.boundzsetOps("z_key").add("c",10);
    	set = redisTemplate.boundzSetOps("z_key").range(0,-1);
        System.out.println("zset有序集合中的所有元素:" + set);
    }
}

10.SpringBoot專案部署

目標:將Spring Boot專案使用maven指令打成jar包並執行測試

分析:
1.需要新增打包元件;將專案中的資源、配置、依賴包打到一個jar包中;可以使用maven的package ;

<build>
    <plugins>
    	<!--打jar包時如果不配置該外掛,打出來的jar包沒有清單檔案-->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

2.部署: java -jar 包名