Java Spring-重构-将实体常量移动到配置(application.properties)
从代码中移动常量的最佳方法是:Java Spring-重构-将实体常量移动到配置(application.properties),java,spring,spring-boot,configuration,refactoring,Java,Spring,Spring Boot,Configuration,Refactoring,从代码中移动常量的最佳方法是: @Entity public abstract class Post { ... private static final int HOTPOST_LIKE_TRESHOLD = 6; ... public long increaseLikeCounter() { likesCount++; if (likesCount >= HOTPOST_LIKE_TRESHOLD) { thi
@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像TRESHOLD一样从类中移开,但我希望保持increaseLikeCounter方法的位置。将Post更改为:
@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;
}
...
在您的应用程序中。属性添加
simplePost.hotpostLikeTreshold = 6
编辑:
Post不应该决定它是否被认为是热的-应该有另一个实体编码此规则,并且您可以在那里拥有SHADL as bean属性。好的,但是在其他情况下,Post应该决定,并且它必须使用我想要移动到配置的值,但不想传递方法参数,这又如何呢?问题在于技术上的可能性,而不是商业规则。在实体(不是由spring管理)中使用可配置属性而不通过方法参数传递的最佳方法是什么。如果我们讨论的只是一种技术可能性,那么您可以在spring中自动关联任何对象,只需给它一个唯一的名称。请检查我下面的评论,我们在这里讨论的是JPA@Entity对象。它们不是春豆。我们使用“new”操作符(new SimplePost())或通过EntityManager访问来创建它们。您的soultion如何工作?@msiakis,在这种情况下,您必须将该配置外部化到一个可以由Spring自动连接的位置。
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);
}
}