Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用@Value注释注入单个属性_Java_Spring Boot_Spring Annotations - Fatal编程技术网

Java 使用@Value注释注入单个属性

Java 使用@Value注释注入单个属性,java,spring-boot,spring-annotations,Java,Spring Boot,Spring Annotations,我有一个类,我只希望从属性文件中注入一个属性。 课程是这样的: @Getter public class BatchContext { private final String city; private final String channel; @Value("${table.url: https://www.someurl.com}") private final String url; @Builder publi

我有一个类,我只希望从属性文件中注入一个属性。 课程是这样的:

@Getter
public class BatchContext {

    private final String city;
    private final String channel;

    @Value("${table.url: https://www.someurl.com}")
    private final String url;

    @Builder
    public BatchContext(String city, String channel, @Value("${table.url:https://www.someurl.com}") String url) {
        this.city = city;
        this.channel = channel;
        this.url = url;
    }
}

我只想将country和segment传递到BatchContext,并想从属性文件加载url,但url结果为空,实现这一点的最佳方法是什么。

Madu,似乎您的问题与您的类有关。 它不是Spring上下文的Bean,那么您的@Value不能被Spring注入

尝试将您的类设置为Spring管理的对象,例如@Component:

@Component
public class BatchContext {...
}

为什么有url在那里,table.url应该是键,删除其余的。另外,只需使用@Value一次就足够了,不要用于函数参数部分,构造函数中不需要它,因为它已经通过值注释赋值了。嗨,你能给我举个例子吗。如果我没有在构造函数中添加url,那么它会说我应该将url添加到构造函数中,因为它没有初始化,但是如果我将其添加到构造函数中,那么调用应该提供取消@value的全部用途的值。我希望从属性文件中注入url值,而不让调用者提供该值。那么您的意思是@value annotation仅适用于spring管理的类吗?就是这样,Madu!:)