1. 程式人生 > >javaEE 中spring bean 重複問題

javaEE 中spring bean 重複問題

第一:在典型的基於spring bean的javaEE專案中:webmvc-config.xml中:

<context:component-scan base-package="com.jingoal" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />        
    </context:component-scan>

 必須增加 use-default-filters="false". 否則會把manager,service,dao 等也掃描進去的.


   檢查的一個手段是:讓manger bean 實現  InitializingBean, 列印日誌檢視,如:

@Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("CalendarEventDynamicJob  + afterPropertiesSet, " + this.hashCode() );        
    }


第二:aop代理命中的類,該類的構造 方法會被呼叫二次,但是 InitializingBean 中的  afterPropertiesSet 僅僅呼叫一次。所以我們不能在spring bean構造方法中觸發任務。一個構造方法不等於一個spring bean.   參考: http://www.4byte.cn/question/439140/controller-class-instantiated-twice-with-spring-aop.html。

保證bean的唯一性 可以使用下面的程式碼:

public class OneBeanGuarantee {
    private static Set<String>  set = new HashSet<String>();
    
    public static synchronized void check(Object o){
        String s = o.getClass().getName();
        if(set.contains(s))
            throw new Error("duplicated bean ["+s+"]");
        set.add(s);
    }
}
 
@Override
    public void afterPropertiesSet() throws Exception {
        OneBeanGuarantee.check(this);
    }