Tag Archives: Spring Error

Spring Error: Bean instantiation via factory method failed StackOverflowError

 

1. Phenomenon

When writing spring program normally, an error is reported suddenly:

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. Analysis and treatment

Several keywords: beancreationexception, beaninstantiation via factory method failed, beaninstantiationexception, stackoverflow error.

It can be analyzed that there is an error in the generated bean, and then we can see that there is a stackoverflow error indicating that there is a memory overflow, which should be caused by an infinite loop.

Look at the code:

	@Bean
	public BlogDao blogDao() {
		BlogDao blogDao=new BlogDao();
		blogDao.setNamedParameterJdbcTemplate(namedParameterJdbcTemplate());//注入namedParameterJdbcTemplate
		return blogDao();
	}

I’ll go. Blogdao () calls blogdao (), and I call myself.

To be amended as follows:

	@Bean
	public BlogDao blogDao() {
		BlogDao blogDao=new BlogDao();
		blogDao.setNamedParameterJdbcTemplate(namedParameterJdbcTemplate());//注入namedParameterJdbcTemplate
		return blogDao;
	}

It’s done!