序文
この記事では、Spring Boot2の基本の下でKotlinを使用する方法について説明し、シームレスに統合して完全にブレンドします。読者をKotlinの構文砂糖に精通するために、著者はいくつかの将来の記事でKotlinの新しい機能と構文砂糖について話します。以下ではあまり言わない、詳細な紹介を見てみましょう
POMファイルを変更し、Spring Boot依存関係を追加します。
<parent> groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <バージョン> 2.0.2.Release </version> </version> </parent> <deprencies> <seprodency> <seprofency> org.springframework.boot </groupid> <artifactid> spring-boot-starter </artifactid> </dependency> <dependency> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-web </artifactid> </dependency> <dependency> <gripwork.springframework.boot </groupid> <artifactid> spring-boot-starter-jdbc </artifactid> </dependency> </dependencies>
その後、MySQL依存関係を追加する必要があります。
<Dependency> groupId> mysql </groupId> <artifactid> mysql-connector-java </artifactid> <version> 5.1.35 </version> </dependency> <dependency> <groupid> com.alibaba </groupid> <artifactid> druid </artifactid> <バージョン> 1.0.14
最後に、Kotlin依存関係を追加します。
<Dependency> groupId> org.jetbrains.Kotlin </groupId> <Artifactid> kotlin-stdlib-jdk8 </artifactid> </dependency> <dependency> groupid> org.jetbrains.kotlin </groupid> <artifactid> kotlin- <GroupId> org.jetbrains.Kotlin </groupId> <Artifactid> kotlin-stdlib </artifactid> </dependency>
Kotlinでは、Data Classにはデフォルトではパラメーターのないコンストラクターがなく、データクラスはデフォルトで最終タイプになり、継承できないことに注意してください。 Spring + Kotlinモードを使用する場合、 @autowaredを使用するとこの問題が発生する可能性があることに注意してください。したがって、Noargを追加して、注釈付きクラスとしてパラメーターのないコンストラクターを生成できます。 Allopenを使用して、注釈付きクラスのファイナルを削除し、継承を許可します。
<プラグイン> <artifactid> kotlin-maven-plugin </artifactid> <groupid> org.jetbrains.kotlin </groupid> <version> $ {kotlin.version} </version> <executions> <execution> <id>コンパイル</id> <ゴール> <Goal> <goal>テストコンパイル</goal> </goal> </execution> </execution> </execution> </execution> <dependencies> <dependency> <dependency> <groupd> org.jetbrains.kotlin </groupid> <artifactid> kotlin-maven-noarg </artifactid> </deprency> </</</</</</</</</</</</</</seprency <GroupId> org.jetbrains.kotlin </groupid> <artifactid> kotlin-maven-alopen </artifactid> <version> $ {kotlin.version} </version> </dependency> </dependencies> </plugin>この時点で、Mavenの依存関係環境は大まかに構成されています。完全なソースコードについては、記事の最後にあるGitHubリポジトリを参照できます。
Spring Boot Default Configurationを使用すると、DataSourceとJDBCtemplate Beanを作成する必要はありません。
SRC/Main/Resources/Application.Propertiesでデータソース情報を構成します。
spring.datasource.datasource.driver-class-name = com.mysql.jdbc.driverspring.datasource.url = jdbc:mysql:// localhost:3307/springboot_dbspring.datasource.username = rootspring.datasource.passord = root
SRC/main/resources/config/source.propertiesでデータソース情報を構成します。
#mysqlsource.driverclassname = com.mysql.jdbc.driversource.url = jdbc:mysql:// localhost:3306/springboot_dbsource.username = rootsource.password = root
ここで、DataSourceとJDBCTEMPLATEを作成します。
@configuration @enabletransactionmanagement @propertySource(value = *arrayof( "classpath:config/source.properties"))open beanconfig { @autowired private lateinit var env:環境@bean open dataSource():dataSource {val dataSource = druiddatasource = DataSource()DataSource()DataSource()DataSource()DataSource env !!。getProperty( "source.driverclassname") @bean open fun jdbctemplate():jdbctemplate {val jdbctemplate = jdbctemplate()jdbctemplate.datasource = dataSource()return jdbctemplate}}}最初に必要なSQLスクリプトを初期化します。
データベース /*!32312存在しない場合は* /`springboot_db` /*!40100デフォルト文字セットutf8* /; `springboot_db`を使用します。 「t_author」が存在する場合はテーブルをドロップします。テーブル `t_author`(` id` bigint(20)null noll auto_incrementコメント「ユーザーID」、 `real_name` varchar(32)null comment`ユーザー名 '、` nick_name` varchar(32)not null comment' not null comment 'user annynomous = birim = ingradb
クラス著者{var id:long? = null var realName:文字列? = null var nickname:string? = null}Interface authordao {fun add(著者:著者):int fun update(著者:著者):int fun delete(id:long):int fun findauthor(id:long):著者?楽しいfindauthorlist():list <turity>}実装クラスを定義し、jdbctemplateを介してデータにアクセスします。
@RepositoryOpen class authordaoimpl:authordao {@autowired private lateinit var jdbctemplate:jdbctemplate override fun add(著者:著者):int {return jdbctemplate.update( "t_author(real_name、nick_name)values(?? Fun Update(著者:著者):int {return jdbctemplate.update( "update t_author set real_name =?、nick_name =?where id =?"、 *arrayof(author.nickname、author.id))} id =? "、id)} andride fun findauthor(id:long):著者? {val list = jdbctemplate.query <turity>( "select * from t_author where id =?"、arrayof <any>(id)、beanpropertyrowmapper(著者:: class.java))return list?.get(0); } override fun findauthorlist():list <turity> {return jdbctemplate.query( "select * from t_author"、arrayof()、beanpropertyrowmapper(著者:: class.java))}}}Interface AuthorService {fun add(著者:著者):int fun update(著者:著者):int fun delete(id:long):int fun findauthor(id:long):著者?楽しいfindauthorlist():list <turity>}実装クラスを定義しましょう。サービスレイヤーは、DAOレイヤーメソッドを呼び出します。これは典型的なルーチンです。
@Service( "AuthorService")Open Class AuthorServiceImpl:authorService {@autowired private lateinit var authordao:authordao override fun upder(著者:著者):int {return this.authordao.update(著者)} long):int {this.authordao.delete(id)} fun findauthor(id:long)をオーバーライドする:著者? {return this.authordao.findauthor(id)} override fun findauthorlist():list <thuthor> {return this.authordao.findauthorlist()}}}効果を示すために、最初にテスト用の安らかなAPIインターフェイスの単純なセットを定義します。
@retycontroller @requestmapping(value = "/authors")class authorcontroller {@autowired private lateinit var authorservice:authorservice/*** query user list*/@requestmapping(method = [requestmethod.get])fun getauthorlist(request:httpservletrequest): this.authorservice.findauthorlist()val param = hashmap <string、any>()param ["total"] = autherlist.size param ["rows"] = authorlist return param}/** queryユーザー情報*/@requestmapping(value = "/{userid:// d+}"長い、リクエスト:httpservletrequest):author {return authorservice.findauthor(userid)?:throw runtimeexception( "query error")} / *** new method* / @requestmapping(method = [requestmethod.post])fun add(@requestbody jsonobject:jsonobject) RealName = jsonObject.getString( "Real_name")val nickname = jsonobject.getString( "nick_name")val著者=著者()著者= java.long.valueof(userid)著者= realname = realname著者著者。 runtimeexception( "new error")}}/***更新方法*/@requestMapping(value = "/{userid:// d+}"、method = [requestmethod.put])fun upder( @pathvariad userid:long、 @requestbody jsonobject:jsonobject){var著者= balideer.findauth jsonobject.getString( "real_name")val nickname = jsonobject.getString( "nick_name")try {if(auther!= null){auther.realname = realname auther.nickname = nickname this.authorservice.update(著者)}}} catch(exection(exection){sport runtimeexcection) Method*/@RequestMapping(value = "/{userId:// d+}"、method = [requestmethod.delete])fun delete( @pathvariable userid:long){try {this.authorservice.delete(userid)} catch(e:exception){throw runtimeexception( ")最後に、SpringkotlinApplicationを通じてプログラムを実行します。
@springBootApplication(scanbasePackages = ["com.lianggzone.demo.kotlin"])オープンクラスSpringkotlinApplication {Fun Main(args:array <string>){springkotlinapplication :: class.java、 *}}}}ここでは、著者はIdeaのエディターRESTクライアントを推奨しています。 IdeaのエディターRESTクライアントは、Intellij Idea 2017.3バージョンでサポートされており、2018.1バージョンで多くの機能を追加しました。実際、IntellijのアイデアのためのHTTPクライアントプラグインです。私による別の以前の記事を参照してください:APIインターフェイスの新しいスキルをすばやくテストする
### queryユーザーリストhttp:// localhost:8080/authorsaccept:application/jsoncontent-type:application/json; charset; charset = utf-8 ### queryユーザー情報http:// localhost:8080/著者/15acce http:// localhost:8080/authorscontent-type:application/json {"user_id": "21"、 "real_name": "liang guizhao"、 "nick_name": "liang guizhao"} ###更新メソッドhttp:// localhost:8080/oturitor/jsson "real_name": "lianggzone"、 "nick_name": "lianggzone"} ### deleteメソッドhttp:// localhost:8080/authors/21accep:application/jsoncontent-type:application/json; charset = utf-8上記のシンプルなケースを通して、Spring BootでKotlinを統合し、Springアプリケーションの初期建設および開発プロセスを簡素化することが非常に簡単であることがわかりました。読者をKotlinの構文砂糖に精通するために、著者はいくつかの将来の記事でKotlinの新しい機能と構文砂糖について話します。
ソースコード
関連例Complete Code:Spring-Kotlin-Samples(ローカルダウンロード)
さて、上記はこの記事のコンテンツ全体です。この記事の内容には、すべての人の研究や仕事に特定の参照値があることを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとることができます。 wulin.comへのご支援ありがとうございます。