引言
之前在百度、CSDN上查询了各种方法,一直都是空指针异常,原因就是static问题。 先上图。 之前把service层用@PostConstruct赋值后就直接用静态去获取成Settings就是这里出的问题。
解决
对于定义的Static变量赋值问题应该把调用的service层以及获取数据全部放在init初始化里。就不会报错。
对于方法而言就直接调用就行。下面是代码
@Component
public class MailConfig {
@Autowired
private SettingsService settingsService;
public static MailConfig mailConfig;
private static final String PROPERTIES_DEFAULT = "mailConfig.properties";
public static String host;
public static Integer port;
public static String userName;
public static String passWord;
public static String emailForm;
public static String timeout;
public static String personal;
public static Properties properties;
@PostConstruct
public void init(){
mailConfig = this;
mailConfig.settingsService = this.settingsService;
try {
MailSettings ms = JSON.parseObject(mailConfig.settingsService.getSettings().getMailSettings(), MailSettings.class);
host = ms.getMailHost();
port = new Integer(ms.getMailPort());
userName = ms.getMailUsername();
passWord = ms.getMailPassword();
emailForm = ms.getMailUsername();
timeout = ms.getMailTimeout();
personal = ms.getPersonal();
}catch (Exception e) {
e.printStackTrace();
}
}
public static void xx(){
mailConfig.settingsService.xx();
}
}
评论区