第一:在典型的基于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);
}