如何通过Spring @PostConstruct初始化最终变量?

时间:2014-11-15 03:13:56

标签: 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);

    }
..
}

我想初始化变量“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"));
    }

任何人都可以通过更好的方式解决它吗?

1 个答案:

答案 0 :(得分:3)

我相信你可以通过构造函数注入实现你想要的东西:

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