使用 @Value 注解来注入单个属性

huangapple go评论180阅读模式
英文:

Using @Value annotation to Inject single property

问题

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

@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;
    }
}

我想只传递countrysegmentBatchContext,并且想从属性文件中加载url,但url结果为null,最好的方法是什么?

英文:

I have a class in which i want only one property to be injected from the properties file.
The class is like this:

@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;
    }
}

I wanted to just pass country and segment to the BatchContext and wanted to load url from the properties file but the url turns out to be null, whats the best way to achieve this.

答案1

得分: 0

马杜,看起来你的问题与你的类相关。
它不是 Spring 上下文的 Bean,所以你的 @Value 无法被 Spring 注入。

尝试将你的类设置为 Spring 管理的对象,例如使用 @Component 注解:

@Component
public class BatchContext {...}
英文:

Madu, it seems your problem is related just to your class.
It is not a Bean for Spring context, then your @Value cannot be injected by Spring.

Try setting your class as an object managed by Spring, e.g. @Component:

@Component
public class BatchContext {...
}

huangapple
  • 本文由 发表于 2020年9月15日 04:58:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63891762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定