Issue
I am getting this error when trying to use @autowire, @configuration, @bean, @Repository in my Spring MVC project
Could not autowire field: private com.sachin.dao.StockDaoImpl com.sachin.myapp.HomeController.stockDao;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.sachin.dao.StockDaoImpl] found for dependency:
Please let me know what mistake I am making. I am new to Spring MVC and dependency injection.
Here is my controller code. I am trying to inject StockDaoImpl in the controller.
@Controller
public class HomeController {
@Autowired
private StockDaoImpl stockDao;
@RequestMapping(value = "/stockgoogle/", method = RequestMethod.GET)
public @ResponseBody Stock stockGoogle(Locale locale, Model model) {
//StockDaoImpl stockDao = new StockDaoImpl();
Stock s=stockDao.listGoogle();
model.addAttribute("s", s );
return s;
}
}
My Service Implementation is below. I have used @Repository annotation here with "stockDao" which is my variable name in controller that I want to inject
@Repository("stockDao")
public class StockDaoImpl implements StockDao {
@Override
public Stock listGoogle() {
Stock s = null;
try {
... //some code
String name = rs.getString("Name");
s = new Stock(name);
...
} catch (Exception e) {
}
return s;
}
}
Also I have created a configuration class separately. I am using this to define my bean. I am only using this to specify bean and have not imported it anywhere in the code.
@Configuration
public class BeanConfiguration {
@Bean
public StockDaoImpl stockDao(){
return new StockDaoImpl();
}
}
Am I missing something here. From looking at the error it looks like the @Bean annotation is not visible to the factory. Do I have to do anything else other than annotating the @configuration class.
I might also be using the annotations in a wrong way. I could be making a mistake in how I am using @Autowired or @Repository.
Can you please help.
Solution
I think this might be your issue:
"Also I have created a configuration class separately. I am using this to define my bean. I am only using this to specify bean and have not imported it anywhere in the code."
Somewhere you need to tell Spring to look for BeanConfiguration
. You can do this in your applicationContext.xml
file (assuming you have one) as follows:
<context:component-scan base-package="com.sachin.config" />
This assumes BeanConfiguration is in the com.sachin.config
package.
If you can't find where to put this it may be helpful to share your web.xml file.
Answered By - markwatsonatx