当前位置: 代码网 > it编程>编程语言>Java > SpringBoot注入静态属性或静态对象的方法

SpringBoot注入静态属性或静态对象的方法

2024年12月22日 Java 我要评论
springboot注入静态属性或静态对象前言我们在使用springboot为一些静态属性或者静态对象注入时会发现注入不成功。我们可以以下这几种方式把需要注入的值注入到静态属性中。setter方式注入

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注入静态属性内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com