v11*_*v11 6 java spring dependency-injection
我必须初始化一些最终变量,但这些值需要由 Spring Properties 读取
public class CrawlerClient{
@Autowired
@Qualifier("crawlerProperties")
private Properties crawlerProperties;
private Integer final maxTopic;
public static void main(String[] args) {
//initialize();
}
@PostConstruct
private void initialize(){
List<Topic> topics = topicBusiness.getAll();
List<Blogger> bloggers = bloggerBusiness.getAll();
List<Clue> clues = clueBusiness.getAll();
ClueQueue.addAll(clues);
TopicQueue.addAll(topics);
BloggerQueue.addAll(bloggers);
}
..
}
Run Code Online (Sandbox Code Playgroud)
我想初始化“maxTopic”变量,但值在属性中,所以我无法在构造中执行此操作,我该怎么做?我只知道删除“final”键。最后,我是这样做的:
final Integer maxTopic;
final Integer maxBlogger;
final Integer maxClue;
@Autowired
public CrawlerClient(@Qualifier("crawlerProperties")Properties crawlerProperties){
this.maxTopic = Integer.parseInt(crawlerProperties.getProperty("MaxTopic"));
this.maxBlogger = Integer.parseInt(crawlerProperties.getProperty("MaxBlogger"));
this.maxClue = Integer.parseInt(crawlerProperties.getProperty("MaxClue"));
}
Run Code Online (Sandbox Code Playgroud)
有人能用更好的方法解决吗?
我相信你可以通过构造函数注入实现你想要的:
@Component
public class CrawlerClient{
private Properties crawlerProperties;
private final Integer maxTopic;
@Autowired
public CrawlerClient(@Qualifier("crawlerProperties") Properties crawlerProperties,
@Value("maxTopic") Integer maxTopic){
this.crawlerProperties = crawlerProperties;
this.maxTopic = maxTopic;
List<Topic> topics = topicBusiness.getAll();
List<Blogger> bloggers = bloggerBusiness.getAll();
List<Clue> clues = clueBusiness.getAll();
ClueQueue.addAll(clues);
TopicQueue.addAll(topics);
BloggerQueue.addAll(bloggers);
}
..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10547 次 |
| 最近记录: |