开发者

How to make sure <context:annotation-config/> is set in classes depending on it?

Spring provide a nice feature that allow programmer to define annotations in java source code to setup @Value("systemProp:defaultvalue") and other 开发者_StackOverflow中文版injected dependency.

However, in some case we may forget to enable the <context:annotation-config/> in a mixed XML and annotation spring program.

Is there a way, an utility method or a pattern to put in the java class to enforce the <context:annotation-config/> is not being forgotten?


Write a test case that fails if <context:anotation-config/> is not configured right.


If you really want to check if in production, then define a default value and inject this default value. Then you need to check it in the constructor for example. public class Demo() {

  @Value("default");
  private String check;

  public Demo() {
     assert "default".equals(check) : "It seams that anntation-config is not enabled";
  }
}

Does not work because the Value is injected after the constructor is invoked.

If @Autowired is supported the you can have it all in an seperate method:

public class Demo2 {   

    @Autowired
    public void checkAnnotationConfigEnabled(
                          @Value("default") String check) {
        assert "default".equals(check);
    }
}

If your problem is not that you need to enable anntation-config for each class then it would be enougth to have one bean that implements this check logic. If not, and do not want to put this lines in every class, then you can do it with AspectJ intertype declartions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜