blog

Java開発者として、このSpringBootチュートリアルは、あなたが本当に見る必要がある!

2、設定MyBatis:エンティティクラスのエイリアスパッケージ、ログ、マッピングファイルなど。 マッパーを介して:あなたは、すべてのSQLステートメントをスプライシングを与えるので、達成することがで...

Nov 18, 2020 · 13 min. read
シェア

springbootとは?

springboot springプロジェクトに基づいて雛形をビルドする
役割: 設定と依存関係の管理を簡略化できる
特徴:高速ビルド、組み込みアプリケーションサーバー、自動設定、コード生成なし、xml設定なし

はじめに

1.親依存関係を導入し、springbootのバージョン2.1.5を指定します。

2.ランチャークラスの追加

3.ブートストラップクラスの作成

4.プロセッサを書く

pom.xml

maven依存のバージョンを管理する
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://..//..0"
 xmlns:xsi="http://..//-ce"
 xsi:schemaLocation="http://..//.. http://..//-...sd">
 <modelVersion>4.0.0</modelVersion>
 springboot管理依存バージョン
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.5.RELEASE</version>
 </parent>
 <groupId>.lxg</groupId>
 <artifactId>springboot_luoxg_day01_01</artifactId>
 <version>1.0-SNAPSHOT</version>
 JDK 
 <properties>
 <java.version>1.8</java.version>
 </properties>
 SpringBoot 
 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 </dependencies>
</project>

controller

package.lxg.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
//返される結果は文字列
@RestController
public class HelloController {
 @GetMapping("hello")
 public String helloSpringBoot() {
 return "Hello SpringBoot!";
 }
}

Application

package.lxg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.swing.*;
@SpringBootApplication //は現在がブートストラップクラスであることを示す
public class Application {
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
}

最初に: DataSourceデータソースの設定

jdbc.properties設定ファイル

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork

jdbcConfig構成クラスを作成します。

package.lxg.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Configuration// アノテーションの役割、テーブル名は現在設定クラスである
@PropertySource("classpath:jdbc.properties") //設定ファイルをロードする
public class JdbcConfig {
 //Value 設定ファイルのデータを注入する
 @Value("${jdbc.driverClassName}")
 private String driverClassName;
 @Value("${jdbc.url}")
 private String url;
 @Value("${jdbc.username}")
 private String username;
 @Value("${jdbc.password}")
 private String password;
 @Bean("dataSource")
 public DataSource dataSource() {
 DruidDataSource dataSource = new DruidDataSource();
 dataSource.setDriverClassName(this.driverClass);
 dataSource.setUrl(this.url);
 dataSource.setUsername(this.username);
 dataSource.setPassword(this.password);
 return dataSource;
 }
}

データ・ソースの直接呼び出し

package.lxg.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
//返される結果は文字列
@RestController
public class HelloController {
 @Resource(name = "dataSource")
 private DataSource dataSource;
 @GetMapping("hello")
 public String helloSpringBoot() {
 System.out.println(dataSource);
 return "Hello SpringBoot!";
 }
}

番目: DataSource データ・ソースの構成

application.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork
package.lxg.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Configuration
@PropertySource("classpath:application.properties")
public class JdbcConfig {
 @Bean("dataSource")
 @ConfigurationProperties(prefix = "jdbc")
 public DataSource dataSource() {
 DruidDataSource dataSource = new DruidDataSource();
 return dataSource;
 }
}

つ目:ymlファイルの設定方法

#一般的なデータ構成
name: tanakasan
#オブジェクトの設定
person:
 name: tanakasan
 age: 18
 addr: Tokyo
#行オブジェクトの設定
person1: {name: tanakasan,age: 18,addr: Tokyo}
#設定データ、コレクション
city:
 - Tokyo
 - tianjing
 - chognqing
#行の設定データ、コレクション
city1: [Tokyo,tianjing,chongqing]
#設定データ、コレクション
student:
 - name: tom
 age: 18
 addr: Tokyo
 - name: lucy
 age: 17
 addr: tianjing
#行の設定データ、コレクション
student1: [{name: tom,age: 17,adrr: tianjing},{name: tom1,age: 16,adrr: tianjing}]
#map  
map:
 key1: value1
 key2: value2

ymlファイルの取得方法

1, @Valueアノテーションで値を取得します。

 @Value("${name}")
 private String name;

2、アノテーション@ConfigurationPropertiesコンフィギュレーション

コンフィギュレーション

person:
 name: tanakasan
 age: 18
 addr: Tokyo

クラスメソッド

@Controller
@ConfigurationProperties(prefix = "person")
public class Quick3Controller {
 private String name;
 private String addr;
 @RequestMapping("/quick3")
 @ResponseBody
 public String quick2(){
 return name + " " + addr;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getAddr() {
 return addr;
 }
 public void setAddr(String addr) {
 this.addr = addr;
 }
}

yml設定ファイルの例

application.yml

jdbc:
 driverClassName: com.mysql.jdbc.Driver
 url: jdbc:mysql://localhost:3306/account
 username: root
 password: lncnetwork
spring:
 profiles:
 active: a,b//aとbのyml設定ファイルをアクティブにする

application-a.yml

luoxg: 名前: luoxg

application-b.yml

lncnetwork: 名前: nb

HelloController

luoxg:
 name: luoxg

tomcat ポートの変更

サーバ: ポート: 80

スプリングブート静的リソース格納パス

lncnetwork:
 name: nb

インターセプター

1.HandlerInterceptorを実装した独自のインターセプタークラスを作成します。

@RestController
//@PropertySource("classpath:application.yml") //設定ファイルをロードする
public class HelloController {
 @Resource(name = "dataSource")
 private DataSource dataSource;
 @Value("${luoxg.name}")
 private String luoxg;
 @Value("${lncnetwork.name}")
 private String lncnetwork;
 
}

2.WebMvcConfigurerを実装する設定クラスを作成します。

server:
	port: 80

トランザクション管理

1.トランザクション関連のランチャー依存関係、mysql 関連の依存関係の追加

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };

2.データベース接続プール光設定

package.lxg.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 log.debug("MyInterceptor -- preHandle ");
 return true;
 }
 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
 log.debug("MyInterceptor -- postHandle ");
 }
 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 log.debug("MyInterceptor -- afterCompletion ");
 }
}

3.擬似アクセスデータクラスの書き込み

トランザクションのサポート

package.lxg.config;
import.lxg.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
// インターセプターを登録する
 @Bean
 public MyInterceptor myInterceptor() {
 return new MyInterceptor();
 }
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
 }
}

SpringBoot mybatis

1.スターター依存関係の追加

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

2.MyBatisを設定します: エンティティクラスのエイリアスパッケージ、ロギング、マッピングファイルなど。

spring:
 datasource:
 driver-class-name: com.mysql.jdbc.Driver
 url: jdbc:mysql://localhost:3306/account
 username: root
 password: lncnetwork

3.MapperScanの設定

package.lxg.service;
import.lxg.domain.Account;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountService {
 public void save(Account acc) {
 System.out.println("アカウント情報を保存する");
 }
 @Transactional//トランザクションサポートを有効にする
 public Account selOne(int id) {
 return new Account();
 }
}

## SpringBootの汎用マッパーの統合は、マッパーを介して:すべてのSQLステートメントをスプライシングするため、達成することができます、すべてのマッパーは、任意のメソッドを記述する必要はありませんもSQLステートメントです。開発効率が向上します。

1.ランチャー依存の追加

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

2.AccountMapperの継承マッパー化

mybatis:
 #エンティティクラスのエイリアスパス
 type-aliases-package:.lxg.pojo
 #マッピングファイルのアドレス
 mapper-locations: classpath:mapper/*.xml
 #設定ログ
 configuration:
 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.起動ブートストラップ・クラスの Mapper スキャン・アノテーションを修正します。

package.lxg;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.swing.*;
@SpringBootApplication
//すべてのビジネスマッパーのためにmybatisインターフェースをスキャンする
@MapperScan(.lxg.mapper")
public class Application {
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
}

4.JAPアノテーションを追加するために、Accountエンティティ・クラスを修正します。

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

5.ビジネス機能を実現するために AccountService を修正します。

package.lxg.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
 private Integer id;
 private String name;
 private Float money;
}

6.テスト

package.lxg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
//すべてのビジネスマッパーのためにmybatisインターフェースをスキャンする
@MapperScan(.lxg.mapper")
public class Application {
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
}

SpringBoot Junit

springbootでテストクラスを書くには、@SpringBootTestをクラスに追加する必要があります。

1.junitランチャーを追加

package.lxg.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "account")
public class Account {
 @Id
 //プライマリキーバックフィル
 @KeySql(useGeneratedKeys = true)
 private Integer id;
 @Column(name = "name")
// サポートハンプ
 private String name;
 @Column(name = "money")
 private Float money;
}

2.テストクラスを書く

package.lxg.service;
import.lxg.domain.Account;
import.lxg.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountService {
 @Autowired//自動アセンブリ
 private AccountMapper accountMapper;
 public void saveAccount(Account acc) {
 accountMapper.insertSelective(acc);
 }
 @Transactional
 public Account findById(int id) {
 Account account = accountMapper.selectByPrimaryKey(id);
 return account;
 }
}

SpringBoot Redis

1.スタートアップスターターの依存関係を追加; spring-boot-starter-data-redis

package.lxg.controller;
//返される結果は文字列 
@RestController
public class HelloController {
 @Autowired
 private AccountService accountService;
 @RequestMapping("findById/{id}")
 public Account findById(@PathVariable Integer id) {
 return accountService.findById(id);
 }
}

2.applciation.ymlでredisの接続パラメータを設定します;

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

3.5つのデータでredisを操作するためにRedisTemplateを適用するテストクラスを書きます。

package.lxg.service;
import.lxg.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountServiceTest {
 @Autowired
 private AccountService accountService;
 @Test
 public void saveAccount() {
 Account account = new Account();
 account.setName(" ");
 account.setMoney(99999F);
 System.out.println(account);
 accountService.saveAccount(account);
 System.out.println(account);
 }
 @Test
 public void findById() {
 Account byId = accountService.findById(20);
 System.out.println(byId);
 }
}

SpringBootプロジェクトのデプロイ

1.パッケージングコンポーネントは、プロジェクトのリソース、設定、jarパッケージに依存するパッケージに追加する必要があります。

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

2.デプロイメント:java -jarパッケージ名

 redis:
 host: localhost
 port: 6379

自動設定の原則

1.すべての自動構成クラスはspring.factoryファイルで定義されます。

2.コンフィギュレーションプロセス

package.lxg.redis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sound.midi.Soundbank;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
 @Autowired
 private RedisTemplate redisTemplate;
 @Test
 public void testRedis1() {
//  
 redisTemplate.boundValueOps("name").set(" ");
 System.out.println(redisTemplate.opsForValue().get("name"));
// hash  
 redisTemplate.boundHashOps("h_key").put("name","luoxg");
//  key
 redisTemplate.boundHashOps("h_key").keys();
//  value
 redisTemplate.boundHashOps("h_key").values();
 System.out.println(redisTemplate.boundHashOps("h_key").get("name"));;
// list  
 redisTemplate.boundListOps("names").leftPush("l");
 redisTemplate.boundListOps("names").leftPush("x");
 redisTemplate.boundListOps("names").leftPush("g");
// リストを取得して値を取得する
 System.out.println(redisTemplate.boundListOps("names").range(0,-1));
// set  
 redisTemplate.boundSetOps("ages").add("1","23","19");
 System.out.println(redisTemplate.boundSetOps("ages").members());
// sorted set 順序付きコレクション
 redisTemplate.boundZSetOps("z_key").add("a",30);
 redisTemplate.boundZSetOps("z_key").add("b",20);
 redisTemplate.boundZSetOps("z_key").add("c",10);
 System.out.println(redisTemplate.boundZSetOps("z_key").range(0,-1));
 }
}

最後に

ご覧いただきありがとうございます、あなたが理解できないものを読んだ後、コメント欄で私に尋ねることができ、記事はあなたが私に承認のうなずきを与えるために覚えておくのに役立つと思いますが、私は毎日Java関連の技術記事や業界情報を共有し、記事に注目し、転送することを歓迎します!

Read next

JavaScriptのデータ型

1. 数値 内部的には、すべての数値は64ビット浮動小数点数として格納されます。つまり、言語の底辺には整数は存在せず、すべての数値は小数です。 数値は、2 から 1024 に最も近い値から 2 から -1023 に最も近い値 (...) の範囲で表すことができます。

Nov 18, 2020 · 3 min read