生成8位随机数的方法及其运用

/**
* 文件名:UserCodeUtil.java
* 文件说明:随机数生成工具
*
*/
  

package com.test;

import java.util.List;
import java.util.Random;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

....省略多处引用包

/**
 * @Description: 生成8位随机数的用户名
 * @author 
 * @date 
 */
public class UserCodeUtil {
   
   private static int min=10000000;
   private static int max=99999999;
   
   private final static Logger log = LoggerFactory.getLogger(UserCodeUtil.class);

   @Autowired
   private SysUserService sysUserService;

   private static UserCodeUtil userCodeUtil;

   @PostConstruct
   public void init() {
      userCodeUtil = this;
      userCodeUtil.sysUserService = this.sysUserService;
   }

   private static SysUserService getSysUserService() {
      return userCodeUtil.sysUserService;
   }

   
   
   
   /**
    * @Description: 生成唯一的用户名(账户)
    * @author 
    * @date 
    * @param prefix 编码前缀
    * @return
    */
   public static String generateUniqueUserCode(String prefix) {
      //生成随机8位随机码
      String sCode=prefix+generateCode();
      try {
         //查询数据库中已存在的用户
         while(true){
            List<SysUser> userCodeList=getSysUserService().queryByAccount(sCode);
               if(userCodeList.size()<1){
                   break;
               }else{
                  sCode= prefix+generateCode();
               }
           }
      } catch (Exception e) {
         log.error("访问 UserCodeUtil.generateUniqueUserCode() 发生错误,错误信息为" + e.getMessage());
      }
      return sCode;
   }
   
   
   /**
    * @Description: 根据系统参数配置生成唯一的用户名(账户)
    * @author 
    * @date 
    * @return
    */
   public static String getUserCodeFromSysConfig() {
      
      //获取系统参数配置账户名前缀
      String prefix = SysCodeUtil.getString(CommonConstants.SYS_USER_CODE_PREFIX);
      
      //生成随机8位随机码
      String sCode=prefix+generateCode();
      try {
         //查询数据库中已存在的用户
         while(true){
            List<SysUser> userCodeList=getSysUserService().queryByAccount(sCode);
            if(userCodeList.size()<1){
               break;
            }else{
               sCode= prefix+generateCode();
            }
         }
      } catch (Exception e) {
         log.error("访问 UserCodeUtil.generateUniqueUserCode() 发生错误,错误信息为" + e.getMessage());
      }
      return sCode;
   }
   
   /**
    * @Description: 生成8位随机数
    * @author 
    * @date 
    * @return
    */
   public static synchronized int generateCode() {
      Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;
   }

   
   
}

你可能感兴趣的:(java随笔)