问题总结
1、依赖注入为空值
在自定义类中,引入xxxMapper
,出现mapper为空值;
这是由于spring是不管理自定义类的,也就说如果是通过new
关键字创建的对象,在这个对象内的依赖注入是会失效的
举例说明
/** 指令处理类 */
public class CommandHandler {
@Resource
UserMapper userMapper;
}
// 通过new一个对象,这个对象内部的userMapper其实是个空值
解决方法
通过上下文对象,自己手动获取依赖对象
1、首先可以在工具包里面新建一个类,里面是一个上下文对象
package com.example.smtpserver.utils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class ServerApplicationContextHolder {
public static ConfigurableApplicationContext context;
}
2、然后在运行入口,对该对象赋值
@SpringBootApplication
@MapperScan("com.example.smtpserver.mapper")
public class SmtpServerApplication {
public static void main(String[] args) {
ServerApplicationContextHolder.context = SpringApplication.run(SmtpServerApplication.class, args);
}
}
3、通过上下文对象,获取bean
userMapper = ServerApplicationContextHolder.context.getBean("userMapper", UserMapper.class);
当然可以自己封装一些方法,就可以作为一个工具类来使用了
2、Java处理Base64字符串
base64换行问题
Base64编码包有很多,稍不注意可能会得不到期望的结果引起bug。 使用不同的工具包转化为base64编码。有可能出现不同的效果。 前端转化的base64编码是不换行的。 而后端转化的base64编码是换行的(由使用的转换包决定)。
解决方案: 根据RFC822规定,BASE64.Encoder编码每76个字符,还需要加上一个回车换行 部分Base64编码的java库还按照这个标准实行。 如果不希望换行,换用Apache的 commons-codec.jar。
引入jar包
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
定义两个工具函数,即可
private static String encode(String s) {
byte[] result = Base64
.encodeBase64(s.getBytes(StandardCharsets.UTF_8));
return new String(result, StandardCharsets.UTF_8);
}
private static String decode(String s) {
byte[] decode = Base64.decodeBase64(s);
return new String(decode, StandardCharsets.UTF_8);
}
3、java时间戳和日期转换
public static String getDateString(String timeStamp){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long l = Long.parseLong(timeStamp);
String format = sdf.format(l);
System.out.println("日期格式:"+format);
//输出:日期格式:2020-10-11 10:42:01
}
public static Date getDate(String dateString){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
} finally {
return date;
}
}