使用spring / pojo在类中单独调用某些方法?

时间:2013-08-16 21:59:17

标签: spring methods health-monitoring

我正在为我的应用程序实现运行状况检查。我已经在应用程序中为不同的逻辑系统配置了类,并且编写了检查整个环境条件的方法,如db count,logging errors,cpu process等。

现在我有条件要求我只检查某些条件,即根据主机确定班级中的某些方法。

通过属性文件访问这些方法的最佳方法是什么?请提出你的建议。

感谢。

2 个答案:

答案 0 :(得分:0)

我不喜欢在这种事情上使用反射。它很容易被属性文件更改,然后系统开始生成时髦的错误消息。

我更喜欢直截了当的事情:

controlCheck.properties:

dbCount=true
logger=false
cpuProcess=true

然后代码就像这样(不是真正的代码):

Properties props = ... read property file

boolean isDbCount = getBoolean(props, "dbCount"); // returns false if prop not found
... repeat for all others ...

CheckUtilities.message("Version " + version); // Be sure status show version of this code.
if (isDbCount) {
    CheckUtilities.checkDbCount(); // logs all statuses
}
if (... other properties one by one ...) {
    ... run the corresponding check ...
}

有很多方法可以做到,但这很简单,非常简单。所有配置都在一个属性文件中进行,所有代码都在一个位置,Java程序员可以轻松注释掉不相关的测试或添加新测试。如果你添加一个新的测试,它不会自动在任何地方运行,所以你可以按照自己的时间表推出它,你可以添加一个带有简单shell脚本的新测试,如果你愿意的话。

如果你认为它没有进行特定的测试,那么只需要检查两件事:

  • 是否在属性文件中?
  • 代码的版本是否正确?

答案 1 :(得分:0)

您可以为所需的每项检查定义不同的bean:

<bean id="dbcountBean" class="DBCountHealtCheck" scope="prototype">
  <!-- bean properties -->
</bean>

然后注入操作bean的HealtCheck的bean:

<bean id="healtChecker" class="HealtChecker" scope="prototype">
  <property name="activeChecker"><bean class="PropertiesFactoryBean>
    <property name="location">file:path/to/file</property></bean>
  </property>
  <property name="dbCountCheck" ref="dbCountBean" />
<!-- other properties -->
</bean>

class HealtChecker  {
  private DBCountHealtCheck dbCountChecker;
  private Properties activeChecker;

  public void setDbcount(DBCountHealtCheck dbCountChecker) {
    this.dbCountChecker = dbCountChecker;
  }

  public void setActiveChecker(Properties activeChecker) {
    this.activeChecker = activeChecker;
  }

  public void check() {
    if("true".equals(this.activeChecker.get("dbCount")) {
      this.dbCountChecker.check();
  }
}

如果使用此解决方案无法重新加载文件,请在HealthChecker删除activeChecker属性public void setPropertiesLocation(URL propertiesLocation);,让HealthChecker实现InitializingBean并在afterPropertiesSet()中加载属性{1}}