我有一个类继承了InitializingBean。 用来初始化,部署一些设置。 现在的问题是 被继承的类,总是被调用2次,在网上查了一下资料 ,说是要让此类为单例才会被只调用一次。
所以我在被配置文件里面加入了singleton= "true " 这个设置 不过还是没有成功。请大家帮助!!!
现在的问题是
1.我这样来设计是正确的吗?·
2.如果正确,怎么让此类为单例?
[b]问题补充:[/b]
谢谢你的建议,不过我之前也试过init-method="xxx" 使用这个还是会调用两次
[b]问题补充:[/b]
public class AppCallService implements InitializingBean {
private AppCallDAO appCallDAO;
//private static final List<Integer> registedport = new ArrayList<Integer>();
public void showData(){
ExecutorService threadService;// 线程池
List<Integer> ports = AppProp.getPorts();
if (ports.isEmpty()) {
System.out.println("未配置服务端口");
return;
}
List<AppletCallMonitor> services = new ArrayList<AppletCallMonitor>();
threadService = Executors.newFixedThreadPool(ports.size());
for (Integer port : ports) {
AppletCallMonitor service = new AppletCallMonitor();
//if(registedport.contains(port)) continue;
//registedport.add(port);
System.out.println(port.intValue());
service.setPort(port.intValue());
service.setAppCallDAO(appCallDAO);
services.add(service);
threadService.execute(service);
}
}
public void afterPropertiesSet() throws Exception {
showData();
}
public void setAppCallDAO(AppCallDAO appCallDAO) {
this.appCallDAO = appCallDAO;
}
}
class AppProp{
/**
* 取服务端口
* @return
*/
public static List<Integer> getPorts()
{
List<Integer> ports=new ArrayList<Integer>();
Properties props=getProperties();
if(props == null)
return ports;
String[] portstrs=props.getProperty("PORT","").split(",");
for(String port:portstrs){
int iport=0;
try{
iport=Integer.valueOf(port);
}catch(Exception e){
}
if(iport > 0){
ports.add(new Integer(iport));
}
}
return ports;
}
private static Properties getProperties(){
FileInputStream fstream = null;
try {
fstream = new FileInputStream("E:\\avetti\\workspace-a\\stmNEW\\Target\\WebRoot\\appCall.properties");
Properties prps = new Properties();
prps.load(fstream);
return prps;
}catch(Exception e){
System.out.println(e);
return null;
}
finally{
try{
fstream.close();
}catch(Exception e){
}
}
}
}
[b]问题补充:[/b]
my-servlet.xml
[b]问题补充:[/b]
照lovewhzlq这样设置了依赖关系,还是会执行两次。 不知道什么原因
[b]问题补充:[/b]
是这样的,AppCallService implements InitializingBean 后,afterPropertiesSet里面的 showData() 方法执行了两次。后台信息不会影响吧,因为 我把showdata方法只在控制台输出1句话,它也会执行两次。 我在网上看到的那个提示,也是在讨论InitializingBean (文章提出InitializingBean 会执行两次,是因为BEAN没有单例)和init-method 分别该怎么用。 我都试用过了,都会执行两次。
[b]问题补充:[/b]
to: lovewhzlq
没有。 我想继承InitializingBean之后, 就没在其他BEAN去注入过了 。现在我用了一个private static final List registedport = new ArrayList();
来判断是否已经是配置过的端口号。所以占时能解决问题,但是调用两次。总是觉得不安全啊
这个太奇怪了,你是不是有别的bean要注入“appCallService”这个bean
完全可以不用继承了InitializingBean,就用bean的一个属性就可以指定初始化调用的方法
init-method="xxx"
MyService这个类被别的类继承了吗?,把相关的代码和配置粘全一点
这样设置一下依赖关系
等等,我想问下,是哪部分执行了两次,把后台的信息也粘出来
你可以在继承了InitializingBean中添加下列代码
[code="java"] static boolean firstInit=false;
public void afterPropertiesSet()
{
if(firstInit) //for not singleton , then method will be called twice.
{
logger.info(" init already called");
return;
}
else
firstInit=true;[/code]
注意firstInit 是静态的