在寫工具類時往往需要用到配置文件的信息,在使用@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