Spring-mybatis connection fails with UnsatisfiedDependencyException - spring

I am relatively new to Spring, and am having problem with establishing spring-mybatis setup environment. Here is my code. The exception I am getting is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController for com.infosender.service.UserServiceImpl.
I don't get this issue. Because the UserServiceImpl object is autowired in LoginController and UserServiceImpl class is autowired to UserDaoMapper interface, there should be a bean named UserServiceImpl. Why could be the reason for the bean not found?
package com.infosender.controller;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.infosender.user.User;
import com.infosender.user.UserDao;
import com.infosender.user.UserDaoMapper;
import com.infosender.service.UserService;
import com.infosender.service.UserServiceImpl;;
#Controller
public class LoginController {
//UserService userService = UserService.getInstance();
#Autowired
UserServiceImpl userServiceImpl;
#RequestMapping(value="/login", method=RequestMethod.POST)
public String handleRequestInternal(
#ModelAttribute("username") String user_id,
#ModelAttribute("password") String user_pw
) {
User user = null;
try {
user = userServiceImpl.getUserByIdAndPw(user_id, user_pw);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user == null) {
return "login_fail";
}
return "main_menu";
}
}
And here is UserService and UserServiceImpl
package com.infosender.service;
import java.sql.SQLException;
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.infosender.user.User;
import com.infosender.user.UserDao;
public interface UserService {
public User getUserByIdAndPw(String user_id, String user_pw)throws SQLException;
}
package com.infosender.service;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.infosender.user.User;
import com.infosender.user.UserDao;
import com.infosender.user.UserDaoMapper;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDaoMapper userDaoMapper;
public User getUserByIdAndPw(String user_id, String user_pw)throws SQLException {
return userDaoMapper.getUserByIdAndPw(user_id, user_pw);
}
}
Here I have UserDao and UserDaoMapper
package com.infosender.user;
import java.sql.SQLException;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
#Repository
public class UserDao implements UserDaoMapper{
#Autowired
private SqlSessionTemplate sqlSession;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public User getUserByIdAndPw(String user_id, String user_password) {
UserDaoMapper mapper = sqlSession.getMapper(UserDaoMapper.class);
return mapper.getUserByIdAndPw(user_id, user_password);
//return sqlSession.selectOne("com.infosender.user.UserDaoMapper.getUserByIdAndPw");
}
}
package com.infosender.user;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
public interface UserDaoMapper {
public User getUserByIdAndPw(#Param("user_id")String user_id,#Param("user_password")String user_password);
}
And the below is root-context.xml configuration.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config/>
<!-- org.apache.commons.dbcp.BasicDataSource -->
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/InfoSender"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:/WEB_INF/spring/mybatis/mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath:*/mappers/*mapper.xml"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- <bean id="userDaoMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.infosender.user.UserDaoMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
-->
<context:component-scan base-package="com.infosender.*" />
</beans>
Here is the entire error log
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.infosender.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:696)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:662)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:710)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:587)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:526)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:169)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.infosender.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1646)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 31 more

To anybody who might view this page.
The problem was in fact in my web.xml file. There I declared two xml files with contextConfigLocation tag: root-context.xml and mybatis-config.xml.
What I did was that I wrote them 'separately', so that (I presume) the latter has somehow overwritten the former one, not creating the sqlSession beans as it ought to.
There were some mistakes in the code as the comments have suggested. But this was the main reason for not created beans.

Related

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'insuranceController':

I am new to Spring and I am trying to make an application for learning but I am getting problems with Autowiring, I am adding my code and Error message HTTP 500. I am working on maven Spring with IntelliJ.
Please Help me....
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${spring.database.class}" />
<property name="url" value="${spring.database.host}" />
<property name="username" value="${spring.database.username}" />
<property name="password" value="${spring.database.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
</beans>
InsuranceController.java
package com.insurance.controller;
import com.insurance.mybatis.dao.InsuranceDAO;
import com.insurance.mybatis.dto.InsuranceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.inject.Inject;
import java.util.List;
#Controller
public class InsuranceController {
#Autowired
InsuranceDAO insuranceDAO;
#RequestMapping(value="/insurance")
public String test( ModelMap modelMap ){
modelMap.addAttribute( "text", "안녕하세요" );
return "mybatis/insurance";
}
#RequestMapping(value="/insuranceList")
public String insuranceList( Model model ){
List<InsuranceDTO> list = insuranceDAO.list();
model.addAttribute("list", list);
model.addAttribute( "text", "안녕하세요" );
return "mybatis/insuranceList";
}
}
InsuranceDAO
package com.insurance.mybatis.dao;
import com.insurance.mybatis.dto.InsuranceDTO;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public interface InsuranceDAO {
public List<InsuranceDTO> list();
}
InsuranceDAOImpl
package com.insurance.mybatis.dao;
import com.insurance.mybatis.dto.InsuranceDTO;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.List;
//#Repository
#Service
public class InsuranceDAOImpl implements InsuranceDAO{
#Autowired
SqlSession sqlSession;
#Override
public List<InsuranceDTO> list() {
return sqlSession.selectList( "insurance.list" );
}
}
InsuranceDTO
package com.insurance.mybatis.dto;
public class InsuranceDTO {
private int insuranceID, insuranceCost;
private String insuranceName, content, type;
public int getInsuranceID() {
return insuranceID;
}
public void setInsuranceID(int insuranceID) {
this.insuranceID = insuranceID;
}
public int getInsuranceCost() {
return insuranceCost;
}
public void setInsuranceCost(int insuranceCost) {
this.insuranceCost = insuranceCost;
}
public String getInsuranceName() {
return insuranceName;
}
public void setInsuranceName(String insuranceName) {
this.insuranceName = insuranceName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Error Message
enter image description here
Below is the Major reason for error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'insuranceController': Unsatisfied dependency expressed through field 'insuranceDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.insurance.mybatis.dao.InsuranceDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:895)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:668)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:591)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1650)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
enter image description here

Unable to inject bean with #Qualifier

I have a use case where I am creating two different thread pool with executor service. One has previously existed and I am creating a new.
We have a Java configuration file where all beans are defined. I have created named beans (#Bean (name = "ExecutorService") and #Bean (name = "ExecutorServiceEx")) like following:
package com.amazon.procurementservice.spring;
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn;
import com.amazon.procurementservice.util.OpenPOItemsUtil; import com.amazon.procurementservice.util.POHeadersUtil; import com.amazon.procurementservice.util.POItemsUtil; import com.amazon.procurementviews.accesors.DynamoDBAccessor; import com.amazon.procurementviews.repositories.OpenPOItemRepository; import com.amazon.procurementviews.repositories.POHeaderRepository; import com.amazon.procurementviews.repositories.POItemRepository; import com.amazon.procurementviews.repositories.dynamodb.DynamoDBOpenPOItemRepository; import com.amazon.procurementviews.repositories.dynamodb.DynamoDBPOHeaderRepository; import com.amazon.procurementviews.repositories.dynamodb.DynamoDBPOItemRepository; import com.amazon.procurementviews.spring.ProcurementViewCommonConfig; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import amazon.odin.awsauth.OdinAWSCredentialsProvider;
#Configuration
#DependsOn("EnvironmentHelper")
public class ProcurementViewDynamoDbConfig extends ProcurementViewCommonConfig {
#Value("${ProcurementService.ProcurementSecondaryViews.DynamoDB.materialName}")
private String materialNameViews;
#Value("${ProcurementService.ProcurementSecondaryViews.DynamoDB.awsRegion}")
private String awsRegionViews;
#Value("${ProcurementService.DynamoDB.getPurchaseOrderItems.threadCount}")
private int threadCount;
#Value("${ProcurementService.DynamoDB.getPurchaseOrderItemExs.threadCount}")
private int threadCountEx;
/**
* Beans for repositories
*/
#Bean
POHeaderRepository poHeaderRepository() {
return new DynamoDBPOHeaderRepository(secondaryViewsViewAccessor(), fnSkuListS3Handler());
}
#Bean
POItemRepository poItemRepository() {
return new DynamoDBPOItemRepository(secondaryViewsViewAccessor());
}
#Bean
OpenPOItemRepository openPoItemRepository() {
return new DynamoDBOpenPOItemRepository(secondaryViewsViewAccessor());
}
#Bean
DynamoDBAccessor secondaryViewsViewAccessor() {
return new DynamoDBAccessor(secondaryViewsDynamoDBClient(), secondaryViewsDynamoDBMapper());
}
#Bean
DynamoDBMapper secondaryViewsDynamoDBMapper() {
return new DynamoDBMapper(secondaryViewsDynamoDBClient());
}
#Bean
AmazonDynamoDB secondaryViewsDynamoDBClient() {
final AmazonDynamoDB client =
AmazonDynamoDBClientBuilder.standard().withCredentials(new OdinAWSCredentialsProvider(materialNameViews)).withRegion(awsRegionViews).build();
return client;
}
#Bean(name = "ExecutorService")
ExecutorService threadPool() {
return Executors.newFixedThreadPool(threadCount);
}
#Bean(name = "ExecutorServiceEx")
ExecutorService threadPoolEx() {
return Executors.newFixedThreadPool(threadCountEx);
}
#Bean
POItemsUtil poItemsUtil() {
return new POItemsUtil(poItemRepository(), threadPool());
}
#Bean
OpenPOItemsUtil openPOItemsUtil() {
return new OpenPOItemsUtil(openPoItemRepository(), threadPool());
}
#Bean
POHeadersUtil poHeadersUtil() {
return new POHeadersUtil(poHeaderRepository(), threadPool());
}
}
And I am using them in another file with #Autowired and #Qualifier like the following :
#Autowired
#Qualifier("ExecutorServiceEx")
private final ExecutorService executorServiceEx;
But I am getting exception like following :
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.amazon.procurementservice.activities.GetPurchaseOrderItemExsActivity': Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.util.concurrent.ExecutorService' available: expected single matching bean but found 2: ExecutorService,ExecutorServiceEx
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.20.RELEASE.jar:4.3.20.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.20.RELEASE.jar:4.3.20.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1198) ~[spring-beans-4.3.20.RELEASE.jar:4.3.20.RELEASE]
I tried with #Resource, but result is same. I also tried to add <context:annotation-config/> in application-config.xml but no luck
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-4.0.xsd
http://www.springframework.org/schema/util classpath:org/springframework/beans/factory/xml/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- The main application context spring configuration -->
<import resource="application/environment.xml" />
<import resource="application/http-server.xml" />
<import resource="application/coral-throttle.xml" />
<import resource="application/service-chain.xml" />
<import resource="common/health-check.xml" />
<import resource="common/hibernate.xml" />
<import resource="common/dao-definitions.xml" />
<import resource="application/hibernate.xml" />
<import resource="common/procurement-infrastructure.xml" />
<import resource="common/procurement-common.xml" />
<!--
Add any beans specific to your application here
-->
<bean class="com.amazon.procurementservice.spring.AuditHistoryConfig" />
<bean class="com.amazon.procurementservice.spring.OpenPOItemConfig" />
<bean class="com.amazon.procurementservice.spring.ProcurementViewDynamoDbConfig" />
<bean class="com.amazon.procurementservice.spring.ProcurementViewElasticSearchConfig" />
<bean class="com.amazon.procurementservice.spring.AmazonProfilingConfig" />
<bean class="com.amazon.procurementservice.spring.MetricsConfig" />
<bean class="com.amazon.procurementservice.spring.POServiceConfig" />
<bean class="com.amazon.procurementservice.spring.ApplicationBean" />
</beans>
Please help identify and fix this issue.

How to catch Spring bean creation error - Injection of autowired dependency?

AdminService.java
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.IAdminDAO;
import dao.IMemberDAO;
public interface AdminService
{
public HashMap<String, Object> adminLogin(String id,String pw);
}
AdminServiceImple.java
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.IAdminDAO;
#Service
public class AdminServiceImple implements AdminService
{
#Autowired
private IAdminDAO adminDao;
#Override
public HashMap<String, Object> adminLogin(String id, String pw)
{
HashMap<String, Object> adminResult = adminDao.selectOne(id);
if(adminResult != null)
{
String opwd = (String) adminResult.get("pw");
if(opwd.equals(pw))
{
if(adminResult.get("authority").equals(true))
{
return adminResult;
}
else
{
return null;
}
}
else
{
return null;
}
}
else
{
return null;
}
}
}
AdminController.java
package controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.AdminService;
import service.AdminServiceImple;
import service.MemberService;
#Controller
public class AdminController
{
#Autowired
public AdminServiceImple adminService;
// 관리자 로그인 폼 페이지
#RequestMapping("admin.do")
public String adminLoginPage()
{
return "adminLoginPage";
}
// 관리자 로그인했을 시 요청
#RequestMapping("adminLoginOK.do")
#ResponseBody
public String adminMainPage(#RequestParam(required=false) String id, #RequestParam(required=false)String pw,HttpSession session,HttpServletRequest req,HttpServletResponse resp)
{
HashMap<String, Object> adminLoginIdentify = adminService.adminLogin(id, pw);
if(adminLoginIdentify != null)
{
return "1";
}
else
{
return "0";
}
}
#RequestMapping("adminPage.do")
public String adminPage(HttpSession session,HttpServletRequest resquest,HttpServletResponse response) throws IOException
{
return "adminMainPage";
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="dao, service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:dao/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="model"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="memberDao">
<property name="mapperInterface" value="dao.IMemberDAO"></property>
<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="adminDao">
<property name="mapperInterface" value="dao.IAdminDAO"></property>
<property name="sqlSessionFactory" ref="SqlSessionFactory"></property>
</bean>
</beans>
that is error code.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminServiceImple': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IAdminDAO service.AdminServiceImple.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IAdminDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
I thought about the cause of the error, but I think it is because I did not insert the service annotation.
However, there is no typos in any way, and everything is written correctly and errors occur. Is there something I don't know?
Can you tell me what caused this error?
And what about the solution?
make sure that AdminDao bean is creating and injecting correctly into
AdminServiceImple
use this tag in your spring-cfg.xml file
<context:component-scan base-package="dao" />
and also scan the controller class using --
<context:component-scan base-package="controller" />
you have to give information of class which are going to use annotation to IOC container to create bean...
A mapper is registered to Spring by including a MapperFactoryBean in your XML config file like follows:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
try this to scan your Service Package and Dao Package.
<context:component-scan base-package="dao, service" />
above code will scan the dao and service package respectively.

Autowiring Controller doesn't work after adding entityManagerFactory bean

I've wrote a spring mvc webserver which uses NEO4j as data backend. Now i want to expand this with cassandra, so the server should be able to use both databases.
I have followed these 2 tutorials on how to combine Kundera (A JPA based Cassandra API):
https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Spring
https://code.google.com/p/kundera/wiki/HowToUseKunderaWithSpring
But i'm not able to add the entitymanagerfactory bean to my applicationcontext.xml file.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
When i do this, spring gives an error that it can not create any of the already existing controllers that my webserver uses.
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private bmsapp.service.DataBasePopulator bmsapp.controller.IndexController.dbPopulator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] for bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 22 more
Those controllers are created by using the #Controller annotation in their class files and by autowiring them in the files where they are used. This works fine normally but when i add the entityManagerFactory bean it suddenly stops working. How is this possible?
My applicationContext file currently looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. -->
<context:component-scan base-package="bmsapp" />
<!-- Activate Spring Data Neo4j repository support -->
<neo4j:config storeDirectory="data/graph.db" base-package="bmsapp.domain" />
<neo4j:repositories base-package="bmsapp.repository" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cassandra_pu"/>
</bean>
<tx:annotation-driven mode="proxy" />
<!-- context:annotation-config / -->
<!-- use this for Spring Jackson JSON support -->
<mvc:annotation-driven />
And my persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="cassandra_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost"/>
<property name="kundera.port" value="9160"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="cassandra"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.cassandra.pelops.PelopsClientFactory" />
<property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider"/>
<property name="kundera.cache.config.resource" value="/ehcache-test.xml"/>
</properties>
</persistence-unit>
SimpleComment domain class:
package bmsapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "SIMPLE_COMMENT", schema = "KunderaExamples#cassandra_pu")
#XmlRootElement(name = "SimpleComment")
public class SimpleComment {
#Id
#Column(name = "COMMENT_ID")
private int id;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "COMMENT_TEXT")
private String commentText;
public SimpleComment() {
}
public SimpleComment(int commentId, String userName, String commentText) {
this.id = commentId;
this.userName = userName;
this.commentText = commentText;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
}
SpringExampleDao:
package bmsapp.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bmsapp.domain.SimpleComment;
#Service
public class SpringExampleDao
{
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public SimpleComment addComment(int id, String userName, String commentText)
{
SimpleComment simpleComment = new SimpleComment(id, userName, commentText);
entityManager.persist(simpleComment);
return simpleComment;
}
public SimpleComment getCommentById(String Id)
{
SimpleComment simpleComment = entityManager.find(SimpleComment.class, Id);
return simpleComment;
}
public List<SimpleComment> getAllComments()
{
Query query = entityManager.createQuery("SELECT c from SimpleComment c");
List<SimpleComment> list = query.getResultList();
return list;
}
}
The relevant part of the stacktrace is:
nested exception is java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
So you need to add a dependency to spring-orm, see http://mvnrepository.com/artifact/org.springframework/spring-orm.
However, I'm not sure that really solves your problem. In the description you're mentioning Neo4j and I cannot see what part of your description relates to that.

Autowired Fails with Spring Junit Test

Writing Junit Tests for my spring application. Because I am new at this I tried starting off by writing a Unit Test for a DAO class that I know works (ran it in JBoss). However, I cannot get it to work as a Unit Test in Eclipse. I keep getting an "Error creating bean... Could not autowire field: NoSuchBeanDefinition".
I saw errors similar to this on StackOverflow and other sites and it always ended up being a syntax error or attempting to autowire the Implementation of the interface as opposed to the Interface, etc. I don't see any of those errors with my code.
I did download Spring-test.jar separately from the Spring configuration that came with the project. Both are from Spring 2.5 however, so I don't think that should be an issue :/
Eclipse comes bundled with JUnit 4.8 and Spring Unit Test doesn't work with that so I downgraded my JUnit to use 4.4
One thing to consider... if you look at the code for my Unit Test you will notice that I autowire two fields: a SimpleJdbcTemplate at the Query Service I want to test. Well if I remove the DrugDao and all references to it, then the SimpleJdbcQuery auto-wires just fine.
Here is the stacktrace for your review:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tst.hcps.glucosemanagement.dataaccess.DrugDaoTest': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:127)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.hcps.glucosemanagement.repository.meds.DrugDao tst.hcps.glucosemanagement.dataaccess.DrugDaoTest.dQuery; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
... 18 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.hcps.glucosemanagement.repository.meds.DrugDao] is defined: Unsatisfied dependency of type [interface com.hcps.glucosemanagement.repository.meds.DrugDao]: expected at least 1 matching bean
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:613)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
... 20 more
Here is the Interface and Implementation:
DrugDao.java
package com.hcps.glucosemanagement.repository.meds;
import java.util.List;
import com.hcps.glucosemanagement.domain.meds.Drug;
public interface DrugDao {
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name);
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName);
}
SpringJdbcDrugQuery.java
package com.hcps.glucosemanagement.repository.meds;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Service;
import com.hcps.glucosemanagement.domain.meds.Drug;
import com.hcps.glucosemanagement.repository.DaoOperations;
#Service
public class SpringJdbcDrugQuery extends DaoOperations implements DrugDao {
private static final Logger logger = Logger.getLogger(SpringJdbcDrugQuery.class);
public List<Drug> searchDrugsByPrimaryName(String facilityId, String name)
{
return searchDrugs(facilityId, name, null);
}
public List<Drug> searchDrugs(String facilityId, String primaryName, String secondaryName)
{
List<Drug> results = null;
StringBuffer sql = new StringBuffer();
HashMap<String, Object> namedParameters = new HashMap<String, Object>();
if(primaryName==null) return null;
sql = new StringBuffer();
sql.append("SELECT");
...
results = simpleJdbcTemplate.query(sql.toString(), new DrugMapper(),
return results;
}
private static final class DrugMapper implements ParameterizedRowMapper<Drug>
{
public Drug mapRow(ResultSet rs, int rowNum) throws SQLException {
Drug drug = new Drug();
drug.setFacilityId(rs.getString("FACILITY_ID"));
drug.setPrimaryName(rs.getString("PRIMARY_NAME"));
drug.setSecondaryName(rs.getString("SEC_NAME"));
return drug;
}
}
}
DrugDaoTest2.java (located in a separate source folder at first, then tried it in the same folder)
package com.hcps.glucosemanagement.repository.meds;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hcps.glucosemanagement.domain.meds.Drug;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={
"classpath:common-test.xml"
})
public class DrugDaoTest2 {
#Autowired
DrugDao dQuery;
#Autowired
SimpleJdbcTemplate queryTemplate;
#Test public void glucoseFetch() {
List<Drug> rslts = dQuery.searchDrugsByPrimaryName(null, "INSU*");
assertTrue(rslts.size()>0);
int i=0;
System.out.println(i);
}
public void setDrugDao(DrugDao drugDao) {
this.dQuery = drugDao;
}
}
common-test.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<!--
Test configuration for Spring/JUnit Testing
-->
<bean id="contextApplicationContextProvider" class="com.hcps.glucosemanagement.spring.ApplicationContextProvider" />
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="beans">
<map>
<entry key="bean:name=Log4jJmxServiceMBean" value-ref="glucosemanagement.Log4jJmxService" />
</map>
</property>
</bean>
<bean id="glucosemanagement.Log4jJmxService" class="com.hcps.glucosemanagement.logging.Log4jJmxService" />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="parameterMappingInterceptor" class="org.springframework.web.portlet.handler.ParameterMappingInterceptor" />
<bean id="viewResolverCommon" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="2"
p:cache="false"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"
/>
<bean id="defaultExceptionHandler" class="org.springframework.web.portlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="../error"/>
<property name="exceptionMappings">
<props>
<prop key="javax.portlet.PortletSecurityException">notAuthorized</prop>
<prop key="javax.portlet.UnavailableException">notAvailable</prop>
</props>
</property>
</bean>
<bean id="simpleParameterJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="hciDataSource" />
</bean>
<bean id="hciDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#//vir-tst.com:1521/qar01.world" />
<property name="username" value="ccuser" />
<property name="password" value="bueno" />
<property name="maxActive" value="30" />
<property name="maxWait" value="30" />
<property name="maxIdle" value="30" />
</bean>
</beans>
My mistake: there was another Spring Configuration file referenced elsewhere that I missed. Adding this field and defining setters in my Unit Test for any autowired fields solved the problem.
I am using this checklist now when these types of errors occur:
Make sure that implementing class of Interface type uses “#Service”
annotation
Make sure beans are configured properly in the XML:
Simplest way is to use:
<context:component-scan base-package="com.customization.packagename" />
This adds all classes under the package name
Or create XML Bean Definitions
I had the similar issue and found that while I could AutoWire classes successfully in Eclipse, surefire required only interfaces to be AutoWired. Especially this occurs only when using Cobertura for instrumenting, so pretty sure there is something wrong with the proxy generation. For now, I have just introduced a new interface as it was appropriate for my use-case but there should definitely be another appropriate solution.
Add a bean definition of type SpringJdbcDrugQuery to common-test.xml
I encounter this problem too, and I just add setter, then it works well.

Resources