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

时间:2017-08-31 10:46:04

标签: 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) {
         this.setStatus(HOT);
      }

      return likesCount;
   }

   ...

}

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

现在将操作封装在Post类中,我可以将HOTPOST_LIKE_TRESHOLD从类中移开,但我希望将increaseLikeCounter方法保留在原来的位置。

1 个答案:

答案 0 :(得分:2)

将帖子更改为:

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

}