在写工具类时往往需要用到配置文件的信息,在使用@Value("${}")注入时出现问题,报空指针异常,获取到的值为空,原因是使用了static修饰,具体原因可参见:工具类使用@Autowired无法注入bean的三种解决方法,下面说说解决方法。
第一种,使用@PostConstruct注解
package ts.util;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:mail.properties")
public class TestUtil {
@Value("${mail.smtp.username}")
private String star2;
private static String star;
@PostConstruct
public void init() {
star = star2;
}
public static void testStar() {
System.out.println(star);
}
}
@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
第二种,在构造函数上使用@Autowired。这种方法必须在构造函数上加上@Autowired,否则会报错:java.lang.NoSuchMethodException: ts.util.TestUtil.<init>(),这个报错原因是因为没有重写无参构造器,但是测试发现,加上无参构造器,虽然不会报错但是却不能正确获取到值。具体原因未知。
package ts.util;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:mail.properties")
public class TestUtil {
private static String star;
@Autowired
public TestUtil(@Value("${mail.smtp.username}")String star) {
TestUtil.star = star;
}
public static void testStar() {
System.out.println(star);
}
}
@Autowired 注解,可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
第三种,就是去掉修饰的static,工具类里的方法和变量均不用static修饰,这样即可正常获取到值,
相应的使用工具类时需要注入。
@Autowired
TestUtil testUtil;
public void test02() {
testUtil.testStar();
}
转自:https://blog.csdn.net/hunt_er/article/details/104992227
参考:https://www.jb51.net/article/230575.htm
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了