ApplicationContextUtils
从 springBean 中,获取 Bean
场景
如果要在一个没有被 spring 托管的类中使用 RedisTemplate 等 需要 @Autowired 自动注入的类, 那么就得用这种方式从 spring 容器中获取需要的 bean
/**
- 用来获取 springboot 创建好的工厂
/
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
/*- 用这个变量保留工厂
/
private static ApplicationContext applicationContext;
/* - 将创建好的工厂 以参数的形式传递给这个类
- @param context 创建好的工厂
/
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
/* - 通过 bean 的名称从工厂中获取对象的方法
- @param beanName bean的名称
*/举例:getBean(redisTemplate) 就能获取 RedisTemplate 对象
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
- 用这个变量保留工厂
JWTUtils
封装了生成 jwt 和验证 jwt 的工具类
jwt 相关的依赖选用 java-jwt
RabbitMQUtils
/**
- 获取连接对象和释放资源(关闭通道和关闭连接)
/
public class RabbitMQUtil {
private static final ConnectionFactory factory;
static {
factory = new ConnectionFactory();
// 设置连接 rabbitmq 主机
factory.setHost(“xx.xx.xx.xx”);
// 端口号
factory.setPort(5672);
// 设置连接哪个虚拟主机 ems
factory.setVirtualHost(“/xxx”);
// 设置访问虚拟主机的用户名和密码
factory.setUsername(“xxx”);
factory.setPassword(“xxx”);
}
/*- 定义提供连接对象的方法
- Connection 获取连接对象
/
public static Connection getConnection() {
try {
return factory.newConnection();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
return null;
}
/* - 关闭通道和关闭连接工具
*/
public static void closeChannelAndConnection(Channel channel, Connection conn) {
try {
if (channel != null) {
channel.close();
}
if (conn != null) {
conn.close();
}
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
VerificationCodeUtils
验证码生成工具类
/**
- 生成验证码的工具类
/
public class VerificationCode {
private final int WIDTH = 100;// 生成验证码图片的宽度
private final int HEIGHT = 30;// 生成验证码图片的高度
private final String[] FONT_NAMES = {“宋体”, “楷体”, “隶书”, “微软雅黑”};
private final Color BG_COLOR = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
private Random random = new Random();
private String text;// 记录随机字符串
/*- 获取一个随意颜色
/
private Color randomColor() {
int red = random.nextInt(150);
int green = random.nextInt(150);
int blue = random.nextInt(150);
return new Color(red, green, blue);
}
/* - 获取一个随机字体
/
private Font randomFont() {
String name = FONT_NAMES[random.nextInt(FONT_NAMES.length)];
int style = random.nextInt(4);
int size = random.nextInt(5) + 24;
return new Font(name, style, size);
}
/* - 获取一个随机字符
/
private char randomChar() {
String codes = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
return codes.charAt(random.nextInt(codes.length()));
}
/* - 创建一个空白的BufferedImage对象
/
private BufferedImage createImage() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPEINT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setColor(BG_COLOR);// 设置验证码图片的背景颜色
g2.fillRect(0, 0, WIDTH, HEIGHT);
return image;
}
public BufferedImage getImage() {
BufferedImage image = createImage();
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
String s = randomChar() + “”;
sb.append(s);
g2.setColor(randomColor());
g2.setFont(randomFont());
float x = i WIDTH _ 1.0f / 4;
g2.drawString(s, x, HEIGHT - 8);
}
this.text = sb.toString();
drawLine(image);
return image;
}
/* - 绘制干扰线
*/
private void drawLine(BufferedImage image) {
Graphics2D g2 = (Graphics2D) image.getGraphics();
int num = 5;
for (int i = 0; i < num; i++) {
int x1 = random.nextInt(WIDTH);
int y1 = random.nextInt(HEIGHT);
int x2 = random.nextInt(WIDTH);
int y2 = random.nextInt(HEIGHT);
g2.setColor(randomColor());
g2.setStroke(new BasicStroke(1.5f));
g2.drawLine(x1, y1, x2, y2);
}
}
public String getText() {
return text;
}
public static void output(BufferedImage image, OutputStream out) throws IOException {
ImageIO.write(image, “JPEG”, out);
}
}
使用该工具类
- 获取一个随意颜色
以一个提供验证码的 Controller 为例
@GetMapping(“/verifyCode”)
public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
// 实例化对象
VerificationCode code = new VerificationCode();
// 获取验证码图片
BufferedImage image = code.getImage();
// 获取验证码的字符串
String text = code.getText();
// 将验证码字符串存到 session
session.setAttribute(“verify_code”, text);
// 将图片通过流, 传到前端页面
VerificationCode.output(image, response.getOutputStream());
}
验证码(kaptcha)
可以用 kaptcha 生成验证码
步骤:
导入依赖
@Configuration
public class VerifyCodeConfig {
@Bean
Producer verifyCode() {
// 保存配置
Properties properties = new Properties();
// 宽度
properties.setProperty(“kaptcha.image.width”, “150”);
// 高度
properties.setProperty(“kaptcha.image.height”, “50”);
// 里面包含那些字符
properties.setProperty(“kaptcha.textproducer.char.string”, “0123456789”);
// 长度
properties.setProperty(“kaptcha.textproducer.char.length”, “4”);
// 实例化 DefaultKaptcha
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
// 写入上面的配置
defaultKaptcha.setConfig(new Config(properties));
return defaultKaptcha;
}
}
接口
@Autowired
Producer producer;
@GetMapping(“/vf”)
public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
response.setContentType(“image/jpeg”);
// 获取验证码的文本
String text = producer.createText();
// 将验证码文本写入 session
session.setAttribute(“verifyCode”, text);
// 把验证码文本转换成图片格式 并获取流
BufferedImage bi = producer.createImage(text);
// 把图片验证码写到前端
try(ServletOutputStream out = response.getOutputStream()) {
ImageIO.write(bi, “jpg”, out);
}
}
在 SpringSecurityConfig中设置所有人都可以访问
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(“/vf”).permitAll();