天天看点

Spring报错Bean instantiation via factory method failed StackOverflowError

1. 现象

正常在写Spring程序,突然报错:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:

Error creating bean with name 'blogDao' defined in org.maoge.nameddemo.BeanConfig:

Bean instantiation via factory method failed;

nested exception is org.springframework.beans.BeanInstantiationException:

Failed to instantiate [org.maoge.nameddemo.BlogDao]: Factory method 'blogDao' threw exception;

nested exception is java.lang.StackOverflowError

2. 分析处理

几个关键词:BeanCreationException、Bean instantiation via factory method failed、BeanInstantiationException、StackOverflowError。

可以分析出来是生成bean时报错了,然后看到有StackOverflowError表示有内存溢出,应该是由无限循环。

看代码:

@Bean

public BlogDao blogDao() {

 BlogDao blogDao=new BlogDao();

 blogDao.setNamedParameterJdbcTemplate(namedParameterJdbcTemplate());//注入namedParameterJdbcTemplate

 return blogDao();

}

我去,blogDao()调用blogDao(),自己调用自己了。

修改为:

//为BlogDao注册bean

 return blogDao;

搞定!