1、新增角色實體數據庫
@Entity public class Role { @Id @GeneratedValue private long rid; private String name; //角色名 private String descprtion; //角色描述 public long getRid() { return rid; } public void setRid(long rid) { this.rid = rid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescprtion() { return descprtion; } public void setDescprtion(String descprtion) { this.descprtion = descprtion; } }
2、添加角色操做接口fetch
public interface RoleRepository extends JpaRepository<Role,Long> { }
3、修改UserInfo的用戶角色ui
@ManyToMany(fetch = FetchType.EAGER) //當即從數據庫中進行性加載數據; @JoinTable(name = "UerRole",joinColumns = {@JoinColumn(name = "uid")},inverseJoinColumns = {@JoinColumn(name = "role_id" )}) private List<Role> roles;
4、修改CustomUserDetailServicethis
// 定義權限列表 List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); // 用戶擁有的權限 for (Role role:userInfo.getRoles()){ authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName())); }
5、修改DataInitcode
@Service public class DataInit { @Autowired private UserInfoRepository userInfoRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private RoleRepository roleRepository; @PostConstruct public void dataInit(){ List<Role> roles = new ArrayList<>(); Role adminRole = new Role(); adminRole.setName("admin"); adminRole.setDescprtion("管理員"); Role userRole = new Role(); userRole.setName("normal"); userRole.setDescprtion("普通用戶"); roleRepository.save(adminRole); roleRepository.save(userRole); roles.add(adminRole); roles.add(userRole); UserInfo admin = new UserInfo(); admin.setUsername("admin"); admin.setPassword(passwordEncoder.encode("123")); admin.setRoles(roles); userInfoRepository.save(admin); roles = new ArrayList<>(); roles.add(userRole); UserInfo user = new UserInfo(); user.setUsername("user"); user.setPassword(passwordEncoder.encode("123")); user.setRoles(roles); userInfoRepository.save(user); } }