英文:
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;
}
}
我想只传递country
和segment
到BatchContext
,并且想从属性文件中加载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 {...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论