bean类中的属性值在构造函数中为null [英] Property values in bean class are null in constructor

查看:530
本文介绍了bean类中的属性值在构造函数中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的服务实现类/ bean中的application.properties文件中的值。但是当通过我的配置类初始化bean时,属性值都为null。

I'm trying to use values from my application.properties file in my service implementation class/bean. But when the bean is initialized through my config class, the property values are all null.

配置类:

@Configuration
public class AppConfig {
    @Bean AppServiceImpl appServiceImpl() {
        return new AppServiceImpl();
    }
}

服务等级:

@Component
public class AppServiceImpl implements AppService {
    @Value("${value.one}")
    String value_one;

    @Value("${value.two}")
    String value_two;

    @Value("${value.three}")
    String value_three;

    //values are null here
    public AppServiceImpl() {
        functionOne(value_one, value_two, value_three);
    }
}

application.properties(在src / main / resources下) :

application.properties(under src/main/resources):

value.one=1
value.two=2
value.three=3

做一些调试我可以看到AppConfig类找到了属性文件,如果我尝试声明 @Value($ {value.one})字符串value_one; 在那里显示它已被赋予值 1 as预期。

Doing some debugging i can see that the AppConfig class has found the properties file and if i try to declare @Value("${value.one}") String value_one; there it shows it has been given the value 1 as expected.

但在我的AppServiceImpl类中,所有值都为null。我在这做错了什么?如何在Springboot中正确完成?或者只是春天。

But in my AppServiceImpl class, all the values are null. What am I doing wrong here? How should this be done properly in Springboot? Or just Spring even.

谢谢。

推荐答案

如果你使用构造函数中的值不会立即可用。实际上,他们注入属性。这里发生的是在spring创建一个实例之后它将更新属性值。

If you use the values in the constructor they won't be available right away. Indeed they are injected on attribute. What's happening here is after spring created an instance then it will update the attribute value.

如果你想在构造函数中使用这些值,你应该使用构造函数注入。构造函数注入是最佳实践。

If you want to use those values in the constructor you should use constructor injection. Injection by constructor is a best practice.

public class AppServiceImpl implements AppService {
    String value_one;
    String value_two;
    String value_three;

    //values are null here
    public AppServiceImpl(String value1, String value2, String value3) {
        value_one = value1;
        value_two = value2;
        value_three = value3;
        functionOne(value_one, value_two, value_three);
    }
}

您的配置类

@Configuration
public class AppConfig {
    @Bean AppServiceImpl appServiceImpl(@Value("${value.one}") String value1,  @Value("${value.two}") String value2,  @Value("${value.three}") String value3) {
        return new AppServiceImpl(value1, value2, value3);
    }
}

这篇关于bean类中的属性值在构造函数中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆