Skip to content

Commit f22bdef

Browse files
author
ramazansakin
committed
pre-defined roles initialized not to get "Role not found" error
1 parent a9838ce commit f22bdef

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,35 @@
11
package com.bezkoder.springjwt;
22

3+
import com.bezkoder.springjwt.models.ERole;
4+
import com.bezkoder.springjwt.models.Role;
5+
import com.bezkoder.springjwt.repository.RoleRepository;
6+
import org.springframework.beans.factory.annotation.Autowired;
37
import org.springframework.boot.SpringApplication;
48
import org.springframework.boot.autoconfigure.SpringBootApplication;
59

10+
import javax.annotation.PostConstruct;
11+
import java.util.Optional;
12+
613
@SpringBootApplication
714
public class SpringBootSecurityJwtApplication {
815

16+
@Autowired
17+
private RoleRepository roleRepository;
18+
919
public static void main(String[] args) {
1020
SpringApplication.run(SpringBootSecurityJwtApplication.class, args);
1121
}
1222

23+
@PostConstruct
24+
public void init() {
25+
// Create roles if they don't exist
26+
for (ERole role : ERole.values()) {
27+
Optional<Role> optionalRole = roleRepository.findByName(role);
28+
if (!optionalRole.isPresent()) {
29+
Role newRole = new Role();
30+
newRole.setName(role);
31+
roleRepository.save(newRole);
32+
}
33+
}
34+
}
1335
}

0 commit comments

Comments
 (0)