[Spring] enum ํ™œ์šฉ(RoleType)

enum ํ™œ์šฉ(RoleType)

RoleType์„ ๋งŒ๋“ค ๋•Œ ์—ด๊ฑฐํ˜•(enum)์„ ํ™œ์šฉํ•ด๋ณด์ž.

enum

enum์„ ์“ฐ๊ธฐ ์ „์—๋Š” ์ƒ์ˆ˜๋ฅผ ๋งŒ๋“ค ๋•Œ final static ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜์—ฌ ์‚ฌ์šฉํ•˜์˜€๋‹ค.
์‚ฌ์šฉ์ž์˜ Model์„ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉ์ž์˜ ๋„ค ๊ฐ€์ง€ RoleType์„ ์ •ํ•ด์•ผ ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž.
์‚ฌ์šฉ์ž๋Š” ADMIN, GUEST, MANAGER, MEMBER ๋„ค ๊ฐ€์ง€์˜ Role์ด ์žˆ๋‹ค.

	public static final String ADMIN = "ADMIN";
	public static final String GUEST = "GUEST";
	public static final String MANAGER = "MANAGER";
	public static final String MEMBER = "MEMBER";

์œ„์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ์ •์  ์ƒ์ˆ˜๋ฅผ ๋งŒ๋“  ๋’ค, ํ•„์š”ํ•œ ๊ณณ์—์„œ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๋‹ค.

public class RoleType {
	public static final String ADMIN = "ADMIN";
	public static final String GUEST = "GUEST";
	public static final String MANAGER = "MANAGER";
	public static final String MEMBER = "MEMBER";

	public static void main(String[] args) {
		String user1 = RoleType.ADMIN;
		String user2 = RoleType.GUEST;
	}
}

static์œผ๋กœ ์„ ์–ธ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๊ตณ์ด ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š์•„๋„ ํด๋ž˜์Šค์˜ ์ด๋ฆ„์œผ๋กœ ๋ณ€์ˆ˜๋ฅผ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋‹ค.
๋”ฐ๋ผ์„œ ์œ„์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ RoleType์„ ํ• ๋‹นํ•ด ์ค„ ์ˆ˜ ์žˆ๋‹ค.

ํด๋ž˜์Šคํ˜•์˜ ํ•œ๊ณ„

ํ•˜์ง€๋งŒ, ๋งŒ์•ฝ ํ”„๋กœ๊ทธ๋ž˜๋จธ๊ฐ€ RoleType ํด๋ž˜์Šค๋ฅผ ์ฐธ์กฐํ•ด์„œ ์—ญํ• ์„ ํ• ๋‹นํ•˜๋ฉด ์ข‹๊ฒ ์ง€๋งŒ, ๊ทธ๊ฒŒ ์•„๋‹Œ ์ž„์˜์˜ ๊ฐ’์„ ํ• ๋‹นํ–ˆ์„ ๋•Œ ์‹ค์ˆ˜๋ฅผ ๋ฐฉ์ง€ํ•  ๋ฐฉ๋ฒ•์ด ์—†๋‹ค.

String user3 = โ€œMEMBERRRโ€;

์œ„์™€ ๊ฐ™์ด String ํƒ€์ž…์—์„œ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ์˜คํƒ€๋ฅผ ๋ฐฉ์ง€ํ•  ๋ฐฉ๋ฒ•์ด ์—†๋‹ค.

enum ์‚ฌ์šฉ

enum์„ ์‚ฌ์šฉํ•ด์„œ RoleType์„ ๋งŒ๋“ค์–ด๋ณด์ž.

enum enumRoleType {
	ADMIN, GUEST, MANAGER, MEMBER
}

์œ„์™€ ๊ฐ™์ด enum์„ ๋งŒ๋“ค๊ณ  ๊ฐ RoleType์„ ์—ด๊ฑฐํ•ด ์ฃผ๋ฉด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

package com.vividswan.blog.test;

public class RoleType {
	public static final String ADMIN = "ADMIN";
	public static final String GUEST = "GUEST";
	public static final String MANAGER = "MANAGER";
	public static final String MEMBER = "MEMBER";

	public static void main(String[] args) {
		String user1 = RoleType.ADMIN;
		String user2 = RoleType.GUEST;

		enumRoleType user3 = enumRoleType.MANAGER;
		enumRoleType user4 = enumRoleType.MEMBER;
	}
}

enum enumRoleType {
	ADMIN, GUEST, MANAGER, MEMBER
}

์ƒˆ๋กœ ๋งŒ๋“  user3, user4์˜ ํƒ€์ž…์ด enum์ด๋ฏ€๋กœ ๊ทธ ํƒ€์ž…์— ๋งž๊ฒŒ ํ• ๋‹นํ•  ๊ฐ’์„ ์ค€์ˆ˜ํ•ด์•ผ ํ•œ๋‹ค.
์ด๋Ÿฌํ•œ ๋ฐฉ์‹์œผ๋กœ ์‹ค์ˆ˜๋ฅผ ์‚ฌ์ „์— ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

Entity์—์„œ ์‚ฌ์šฉ

Model์„ ๊ฐœ๋ฐœํ•  ๋•Œ User Entity์—์„œ role์— ๋Œ€ํ•œ column์„ ๋งŒ๋“ ๋‹ค๊ณ  ํ•˜์ž.

@Enumerated(EnumType.STRING)
private enumRoleType role;

์œ„์™€ ๊ฐ™์ด ์„ ์–ธํ•˜๋ฉด role์— ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๋Š” ๋„๋ฉ”์ธ์„ enum์— ์„ ์–ธํ•œ ๋Œ€๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

@Enumerated(EnumType.STRING) ์€ ํ•ด๋‹น enum์ด String ํƒ€์ž…์ด๋ผ๋Š” ๊ฒƒ์„ ์„ ์–ธํ•˜๋Š” ๋ถ€๋ถ„์ด๋‹ค.