Spring中static变量不能@value注入的三种解决方法

2023-04-25 19:48:19

在写工具类时往往需要用到配置文件的信息,在使用@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();
}

 

  • 作者:ds_surk
  • 原文链接:https://blog.csdn.net/hunt_er/article/details/104992227
    更新时间:2023-04-25 19:48:19