2011-12-04 50 views

回答

0

最簡單的方法是配置某種豆與靜態康特變量指望它多久initzalized。

如果該計數器更多的則是零,如果在創建bean時,那麼這個限制它volated和異常應thorwn。

@Component 
public OnlyOneInstanceGuard() { 

    private static int instanceCounter = 0; 


    public OnlyOneInstanceGuard() { 
     if(!isFirstInstance) { 
     throw new RuntimeException(
      "is not the first instance, let the spring context crash!"); 
     } 
    } 

    private syncronized isFirstInstance() { 
     instanceCounter++; 
     return instanceCounter == 1; 
    } 
}