代码示例
如果直接使用@Value注入是什么结果?
/**
- the StaticInjectionUtils
*
- @author Java实用技术手册
- @date 2023-01-17
*/
@Component
public class StaticInjectionUtils {
@Value("${normal.value}")
private String normalValue;
@Value("${static.value}")
private static String staticValue;
@PostConstruct
public void init() {
System.err.println("*** normalValue=" + normalValue);
System.err.println("*** staticValue=" + staticValue);
}
}
// 运行结果
//* normalValue=normal --有结果
//* staticValue=null --无结果
复制代码
😉set注入(推荐)
@Component
public class StaticInjectionUtils {
public static String staticValue;
@Value("${static.value}")
public void setStaticValue(String staticValue) {
StaticInjectionUtils.staticValue = staticValue;
}
@PostConstruct
public void init() {
System.err.println("*** staticValue=" + staticValue);
}
}
// * staticValue=static
复制代码
注意点1:
默认idea的提示set方法会带上static,将导致注入失败,比如
@Value("${static.value}")
public static void setStaticValue(String staticValue) {
StaticInjectionUtils.staticValue = staticValue;
}
复制代码
注意点2:
静态变量不要用this引用,要用类名.变量,虽然你用this也能工作。
@Value("${static.value}")
public void setStaticValue(String staticValue) {
this.staticValue = staticValue;
}
复制代码
至于为什么用this也能生效,知道的同学可以留言讨论~
注意点3:
方法名无所谓,你可以随便改,不信你试试。
😁PostConstruct注入
@Component
public class StaticInjectionUtils {
@Value("${static.value}")
private String staticValue;
public static String STATIC_VALUE2;
@PostConstruct
public void init() {
STATIC_VALUE2 = this.staticValue;
System.err.println("*** staticValue=" + staticValue);
System.err.println("*** STATIC_VALUE2=" + STATIC_VALUE2);
}
}
* staticValue=static
* STATIC_VALUE2=static
复制代码
这里使用了2个知识点:
利用普通@Value变量可以注入,提前完成配置的变量保存。
利用@PostConstruct在@Value之后执行,把普通变量赋值给静态变量。
这里回忆下springbean初始化顺序:方法和注解执行先后顺序为
Constructor -> @Autowired/Value -> @PostConstruct
利用上述原理,可以做很多有用的事情,比如类初始化工作一般专门会写一个init方法。
注意点:
staticValue不能声明为static
这种方法要多定义一个无用变量,所以更推荐set注入。
🤨set变体
@Component
public class StaticInjectionUtils {
private static String staticValue;
@Autowired
public void setStaticValue(@Value("${static.value}") String staticValue) {
System.out.println("set staticValue="+staticValue);
StaticInjectionUtils.staticValue = staticValue;
}
@PostConstruct
public void init() {
System.err.println("*** staticValue=" + staticValue);
}
}
复制代码
这也是set注入的一种变体,方法入参使用@Value注入,然后利用@Autowired,调用此方法注入给static变量。
注意点:
方法不能有static修饰。
方法必须使用@Autowired注解。
以上就是本期内容,希望对你有帮助。