我是靠谱客的博主 欢喜鞋垫,最近开发中收集的这篇文章主要介绍Spring 静态变量/构造函数注入失败的解决方案,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、案例1:Spring对静态变量的注入为空

案例代码如下:

@Component
public class HelloWorld {
   /**
    * 错误案例:这种方式是不能给静态变量注入属性值的
    */
    @Value("${hello.world}")
    public static String HELLO_WORLD;
}

解决方案一:@Value注解加在setter方法上面

@Component
public class HelloWorld {
    public static String HELLO_WORLD;
    
    @Value("${hello.world}")
    public void setHELLO_WORLD(String HELLO_WORLD) {
        this.HELLO_WORLD = HELLO_WORLD;
    } 
}

解决方案二:@PostConstruct注解

因为@PostConstruct注解修饰的方法加在顺序在构造方法之后静态变量赋值之前,所以可以通过该注解解决静态变量属性值注入失败问题:

@Component
public class HelloWorld {
    public static String HELLO_WORLD;
  
    @Value("${hello.world}")
    public static String helloWorld;
    
    @PostConstruct
    public void init(){
        // 为静态变量赋值(值为从Spring IOC容器中获取的hello.world字段值)
        HELLO_WORLD = this.helloWorld;
    } 
}

2、案例2:在构造函数中使用Spring容器中的Bean对象,得到的结果为空

业务场景假设:

eg:我需要在一个类(HelloWorld)被加载的时候,调用service层的接口(UserService)去执行一个方法(sayHello),有些同学可能会在构造函数中通过调用UserService的sayHello()去实现这个需求,但是这会导致一些错误异常,请看下面的示例。

错误演示代码如下:

@Component
public class HelloWorld {
     
   /**
    * UserService注入
    */
    @Autowired
    private UserService userService;

    public HelloWorld(){
       // 这里会报空指针异常:因为 userService 的属性注入是在无参数构造函数之后,如果这里直接使用 userService ,此时该属性值为null,一个为null的成员变量调用sayHello()方法,NullPointException 异常是情理之中呀!
       userService.sayHello("hello tiandai!");
    }
}

解决方案:@PostConstruct注解

由于@PostConstruct注解修饰的方法其生命周期位于构造方法调用之后,在Spring属性值注入之前,所以,该注解可以很好的解决这个业务需求,代码如下:

@Component
public class HelloWorld {
     
   /**
    * UserService注入
    */
    @Autowired
    private UserService userService;

    public HelloWorld(){
    }
  
    @PostConstruct
    public void init(){
       userService.sayHello("hello tiandai!");
    } 
}

补充

关于这一部分问题,还有一些奇奇怪怪的用法

在构造函数里使用@Value注入的属性值获取不到

在配置mqtt连接的时候是在bean初始化的时候就进行连接, 所以要配置连接参数, 当时用的是这样的方式.

结果运行的时候一直会报NullPointer异常,网上找了很多方案都没效果,  后来发现 controller里是可以注入成功的,  那么说明依赖注入是在构造函数之后进行的.     用以下方式可解决.

还有一点 , @Value 属性是不可以static修饰的,否则也取不到值。

到此这篇关于Spring 静态变量/构造函数注入失败的解决方案的文章就介绍到这了,更多相关Spring 静态变量 构造函数注入失败内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是欢喜鞋垫为你收集整理的Spring 静态变量/构造函数注入失败的解决方案的全部内容,希望文章能够帮你解决Spring 静态变量/构造函数注入失败的解决方案所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(123)

评论列表共有 0 条评论

立即
投稿
返回
顶部