0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

アライグマ目撃記録アプリ 環境構築

0
Posted at

目的

アプリが起動して、PostgreSQLに接続できる状態を目指します。
初学者がSpring Bootを頑張って触ってみた学習記事です。
本来はapplication.propertiesにDBパスワードを書くのはNGですので、公開環境では使わないようにして下さい。
また、このファイルをそのままGitHubにpushしないようご注意ください(.gitignore に入れる、環境変数にする、などの対策を)。🙇‍♀️

DB接続

・application.propertiesを編集し、DB接続情報を入力する。

application.propertiesとは

・Spring Bootにおいて、アプリケーションの動作設定をキーと値のペアで記述する設定ファイルのこと。

spring.application.name=アプリケーション名
#JDBCドライバ
spring.datasource.driver-class-name = org.postgresql.Driver 
spring.datasource.url = jdbc:postgresql://localhost:5432/データベース名
spring.datasource.username = DBのユーザー名
spring.datasource.password = DBのパスワード

JDBC(Java Database Connectivity)とは

・Javaプログラムからリレーショナルデータベースにアクセスして操作するための標準JavaAPIのこと。

DBテーブル作成

・SQLでテーブルを作成する。

create table "raccoon"(
id serial,
sighted_date date not null,
sighted_time time not null,
count integer not null,
memo varchar(255),
created_at timestamp,
updated_at timestamp,
primary key(id)
);

・Spring Bootで起動して、コンソールビューに

HikariPool-1 - Starting...
HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@1a2b3c4d
HikariPool-1 - Start completed.

が表示されていればOK。

なぜかログイン認証画面が出る。。。

・この時点でhttp://localhost:8080/と検索すると404エラーではなく、ログインページに。
調べてみると、pom.xmlにSpring Securityの記載があり、Spring Bootが自動的にログイン画面を生成してしまうことが原因だと。(賢い)

・今回はローカル開発(初心者)なので一旦セキュリティはなしで作成しました。

方法

・パッケージ・エクスプローラーでsrc/main/javaを右クリック
・新規→クラス
・パッケージ:com.example.demo.config
・名前:SecurityConfig

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * セキュリティ設定。
 *
 * 開発中は認証をかけず、ログイン画面を出さない。
 * 認証をかけるときは permitAll() を authenticated() に書き換える。
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

      @Bean
      SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
              // すべてのリクエストを認証なしで許可する
              http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
              return http.build();
      }
}

参考記事
Spring Securityの基本的な使い方

・これでログイン画面ではなく404エラーが表示されるようになりました。DBとの接続も、上記のHikariのログで確認できました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?