gpt4 book ai didi

java - Spring - 重构 - 将实体常量移动到配置(application.properties)

转载 作者:行者123 更新时间:2023-11-30 02:24:31 26 4
gpt4 key购买 nike

从代码中移动常量的最佳方法是什么:

@Entity
public abstract class Post {

...

private static final int HOTPOST_LIKE_TRESHOLD = 6;

...

public long increaseLikeCounter() {
likesCount++;

if (likesCount >= HOTPOST_LIKE_TRESHOLD) {
this.setStatus(HOT);
}

return likesCount;
}

...

}

使用 Spring 到配置文件? (即 Spring Boot application.properties)

操作现在封装在 Post 类中,我可以将 HOTPOST_LIKE_TRESHOLD 从类中移走,但我想保留increaseLikeCounter 方法。

最佳答案

将帖子更改为:

@Entity
public abstract class Post {

...

protected abstract Integer getHotpostLikeTreshold();
...

public long increaseLikeCounter() {
likesCount++;

if (likesCount >= getHotpostLikeTreshold()) {
this.setStatus(HOT);
}

return likesCount;
}
...

}

然后扩展该类,例如:

public class SimplePost extends Post {

@Value("${simplePost.hotpostLikeTreshold}")
private Integer hotpostLikeTreshold;

@Override
protected Integer getHotpostLikeTreshold(){
return hotpostLikeTreshold;
}
...

在您的application.properties中添加

simplePost.hotpostLikeTreshold = 6

编辑:

use a Service and getters setters:

@Service
public class SimplePostService{

// wire your property in
@Value("${simplePost.hotpostLikeTreshold}")
private Integer hotpostLikeTreshold;

public Post savePost(...){
Post post = new SimplePost(); // you create your post with 'new'
...
// set your property
post.setHotpostLikeTreshold(this.hotpostLikeTreshold);
...
// save your entity
SimplePostDAO.save(post);
}

}

关于java - Spring - 重构 - 将实体常量移动到配置(application.properties),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45979576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com