springboot注入静态属性或静态对象
前言
我们在使用springboot为一些静态属性或者静态对象注入时会发现注入不成功。
我们可以以下这几种方式把需要注入的值注入到静态属性中。
setter方式注入
代码如下(示例):@value与@autowired都可以使用
@springboottest(classes = application.class)
public class testapplication {
private static daoutil daoutil;
private static string active;
// 这里其实我们只需要一个setter方法
// 即可把springboot中的配置文件中的属性注入到静态属性中
@value("${spring.profiles.active}")
public void setactive( string active) {
testapplication.active = active;
}
@autowired
public void setdaoutil(daoutil daoutil) {
testapplication.daoutil = daoutil;
}
@test
void contextloads() {
system.out.println(getactive());
system.out.println(daoutil);
}
public static string getactive(){
return active;
}
}@postconstruct init方式注入
@autowired
daoutil daoutilproxy;
@value("${spring.profiles.active}")
string activeproxy;
private static daoutil daoutil;
private static string active;
@postconstruct
private void init() {
daoutil = daoutilproxy;
active = activeproxy;
}注意
两种方式都能成功注入对象或属性。 注入成功的前提是属性或对象所在的类是springboot容器的组件(bean)。
// 用ide工具生成静态对象setter方法时会自动的把static的修饰词带上
// 这样也会让注入不成功(作者的惨痛经历😭😭😭)
// 这里我们需要把static去掉即可
public static void setactive(string active) {
testapplication.active = active;
}总结
我们需要可以在组件类中使用@value或@autowired注入静态属性,才能注入成功。否则不成效;
到此这篇关于springboot注入静态属性或静态对象的文章就介绍到这了,更多相关springboot注入静态属性内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论