#Autowired annotation - spring

I have written a small code to check #Autowired annotation in Spring, here is my piece of code
public class Address
{
private String street;
private String City;
private String State;
private String Country;
/* getter setter here */
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Customer
{
private String name;
private Address address;
// other getter setter here
#Autowired
public void setAddress(Address address)
{
this.address = address;
}
}
and springexample.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="address1" class="org.springexamples.Address">
<property name="street" value="vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="addres2" class="org.springexamples.Address">
<property name="street" value="triveni vihar" />
<property name="city" value="dehradun" />
<property name="state" value="Uttarakhand" />
<property name="country" value="India" />
</bean>
<bean id="customer" class="org.springexamples.Customer">
<property name="name" value="deepak" />
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>
and main class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AutowiredQualifierTest
{
public static void main(String[] args)
{
ApplicationContext context= new ClassPathXmlApplicationContext("springexample.xml");
Customer cust = (Customer)context.getBean("customer");
System.out.println(cust.getName() + " " + cust.getAddress().getStreet());
}
}
Ideally it should show an exception as two beans of the same type exist however its picking up bean with id="address1" so i am getting this bean behaviour.

No unique bean of type [org.springexamples.Address] is defined: expected single matching bean but found 2: [address1, addres2]..exception is coming..and it is clearly saying right..so you have to use #Qualifier(your_required_beanid)
for example:
#Qualifier("Address1")
then it will consider id with address1 bean

The exception is thrown. I bet you are doing something wrong. I have tested you code, just to be hundred percent sure and it throws the exception.
Let's take a look to the documentation:
3.4.5.1 Limitations and disadvantages of autowiring
Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown
Also, take a look to this post.

This will give you exception, when spring tries to autoware the address field, it will not find any bean with id address ...rather user Qualifer with proper id so that while autowaring it will pinck the porper object of address from 2 id [address1, address2].

Related

UnsatisfiedDependencyException: Spring MVC project fails to start because of Unsatisfied Dependency

I am trying to start a spring mvc application,
and keep receiving the following error which I cannot solve
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController': Unsatisfied dependency expressed through field 'customerDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
And this is only the first error shown in the console.
Well, I am trying to understand the first part of the whole line, which is
Unsatisfied dependency expressed through field customerDAO Unsatisfied dependency expressed through field customerDAO. It is giving a 500 server error. I cannot find any similar solution, neither see where the error is. Here are my source code files so far:
the entity class
package com.wcorp.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
the dao Interface and its implementation
import com.wcorp.springdemo.entity.Customer;
public interface CustomerDAO {
public List<Customer> getCustomers();
}
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.wcorp.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery =
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}
}
The controller
package com.wcorp.springdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wcorp.springdemo.dao.CustomerDAO;
import com.wcorp.springdemo.entity.Customer;
#Controller
#RequestMapping("/customer")
public class CustomerController {
// need to inject the customer dao
#Autowired
private CustomerDAO customerDAO;
#RequestMapping("/list")
public String listCustomers(Model theModel) {
// get customers from the dao
List<Customer> theCustomers = customerDAO.getCustomers();
// add the customers to the model
theModel.addAttribute("customers", theCustomers);
return "list-customers";
}
}
Here is the spring config file
<?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: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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.wcorp.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent2" />
<property name="password" value="springstudent2" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.wcorp.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
the project build path, jars and tomcat server is fine eclipse is not complaining, spring version is 5.0.2, hibernate version 5.2.17
I found a similar problem described here
Please try to run under Java 8. The problem comes that you use Java 11.
Most of the frameworks are not compatible and are not fully tested on Java 11.

#Qualifier annotation not working

I am trying DI with autowiring and I came across #Qualifier annotation annd tried the following code:
Car.java
package beans;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Qualifier;
public class Car {
#Autowired
#Qualifier("e1")
private Engine engine;
// no need to have setter or constructor
public void showData(){
System.out.println("Engine Model Year : "+engine.getModelyear());
}
}
Engine.java
package beans;
public class Engine {
private String modelyear;
public void setModelyear(String modelyear) {
this.modelyear = modelyear;
}
public String getModelyear() {
return modelyear;
}
}
Spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- activate autowire annotation -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="e1" class="beans.Engine">
<property name="modelyear" value="2017"/>
</bean>
<bean id="e2" class="beans.Engine">
<property name="modelyear" value="2018"/>
</bean>
<bean id="c" class="beans.Car">
</bean>
</beans>
Main.java
package MainClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Car;
public class AutoAnno_Main {
public static void main(String[] args) {
ApplicationContext ap=new ClassPathXmlApplicationContext("resources/spring.xml");
Car c=(Car)ap.getBean("c");
c.showData();
}
}
And the error I am getting is:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'beans.Engine' available: expected single matching bean but found 2: e1,e2
what's wrong in this I think the syntax is correct is there any problem with version
I am using eclipse Oxygen
You just need to add <context:annotation-config /> in your spring.xml. Certain spring annotations are not activated unless this is added. In your case, spring is not reading the #Qualifier annotation without the <context:annotation-config />.
I have tested by adding this and it seems to work.
Update:
Your spring xml needs to have the spring schema for that to detect <context:annotation-config>. Your final xml looks like this.
<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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- activate autowire annotation -->
<context:annotation-config />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="e1" class="beans.Engine">
<property name="modelyear" value="2017"/>
</bean>
<bean id="e2" class="beans.Engine">
<property name="modelyear" value="2018"/>
</bean>
<bean id="c" class="beans.Car">
</bean>
</beans>

Auto wiring with qualifier annotation

I am trying to auto wire my Circle class. I am using a qualifier in order for Spring to able to distinguish between the two Point class beans i have created a qualifier.
public class Circle{
private Point center;
#Autowired
#Qualifier("circleRelated")
public void setCenter(Point center) {
this.center = center;
}
public void draw() {
System.out.println("Drawing Circle");
System.out.println("Centre point is " + center.getX());
}
}
The Point class is as follows
public class Point {
private int x;
public int getX() { return x; }
public void setX(int x) { this.x = x;}
}
The beans.xml is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="circle" class="com.example.Circle"/>
<bean id="pointA" class="com.example.Point">
<qualifier value="circleRelated" />
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="pointB" class="com.example.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
My main class is
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
#SpringBootApplication
public class AutowiredAnnotationApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Circle circle = (Circle) context.getBean("circle");
circle.draw();
}
}
The error I get is
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.example.Point] is defined: expected single matching bean but found 2: pointA,pointB
Why is spring unable to autowire the bean with the given qualifier?
You have to remove this line from your beans.xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
For some reason, it is meddling with your otherwise correct configuration.
The #Qualifier gets the bean id as value. So you have to use "pointA" or "pointB"
public class Circle{
private Point center;
#Autowired
#Qualifier("pointA")
public void setCenter(Point center) {
this.center = center;
}
public void draw() {
System.out.println("Drawing Circle");
System.out.println("Centre point is " + center.getX());
}
}
In general if you skip the #Qualifier - you autowire by type. That means "search in the Spring context a bean of that type and throw an exception if none or more than one is found".
If you add the #Qualifier("someName") that means - "search in the Spring context a bean of that type and with that name and throw an exception if none is found"
Edit:
Take a look at this. I don't think that you need tag at all.
If you wan't to inject some bean using #Autowired the #Qualifier needs the bean id as it's value. For example #Qualifier("pointA") will require a bean with id: pointA.
If you want to inject the bean using only xml you can use ref. You don't need Qualifier for that, only for autowireing.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="circle" class="com.example.Circle">
<property name="center" ref="pointA"/>
</bean>
<bean id="pointA" class="com.example.Point">
<qualifier value="circleRelated" />
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>
<bean id="pointB" class="com.example.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>
</beans>
Edit 2:
See this. I believe that the qualifier tag is taken into account only if you skip the bean id, otherwise the bean id is used.

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.

about a BeanCurrentlyInCreationException, unresolvable circular reference

Good afternoon, I have a project based on apache-cxf v 2.5.2, spring 2.5.6 and hibernate v v 3.2.1. I'm using annotations to mark the units and objects I persist and am having a problem when deploying the war. Giving me the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'storeService': Can not resolve reference to bean 'storeService' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'storeService': Requested bean is Currently in creation: is there an unresolvable loop reference?
this is the applicationContext.xml file
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
">
<context:component-scan base-package="com.aironman.core" />
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hibernate.properties"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${database.hibernate.dialect}
hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider
hibernate.show_sql=true
hibernate.use_sql_comments=true
hibernate.jdbc.batch_size=0
hibernate.hbm2ddl.auto=create-drop
hibernate.default_schema=${hibernate.default_schema}
hibernate.generate_statistics=true
hibernate.cache.use_structured_entries=true
</value>
</property>
<property name="annotatedClasses">
<list>
<value>com.aironman.core.pojos.Usuario</value>
<value>com.aironman.core.pojos.Item</value>
<value>com.aironman.core.pojos.Persona</value>
</list>
</property>
</bean>
</beans>
this is beans.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:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!-- DECLARACION DE LOS ENDPOINTS DE LOS WEB SERVICES-->
<jaxws:endpoint
id="storeService" implementor="#storeService"
implementorClass="com.aironman.core.cxf.service.StoreServiceImpl"
address="/Store" />
</beans>
both files are included on web.xml
this is implementation end point web service, storeService:
**#Service("storeService")
#WebService(endpointInterface = "com.aironman.core.cxf.service.StoreService")
public class StoreServiceImpl implements StoreService** {
private Log log = LogFactory.getLog(StoreServiceImpl.class);
#Autowired
#Qualifier("servicioUsuarios")
private ServicioUsuarios servicioUsuarios;
#Autowired
#Qualifier("servicioItems")
private ServicioItems servicioItems;
#Autowired
#Qualifier("servicioApuntes")
private ServicioApuntesContables servicioApuntesContables;
[B]public StoreServiceImpl()[/B]{
log.info("CONSTRUCTOR SIN tipo StoreServiceImpl...");
}
some methods... getters and setters ...
}
this is ServicioUsuariosImpl file:
package com.aironman.core.service;
**#Service("servicioUsuarios")
public class ServicioUsuariosImpl implements ServicioUsuarios** {
private static ConcurrentHashMap <String,Usuario>hashMapUsuarios = new ConcurrentHashMap <String,Usuario> () ;
private Log log = LogFactory.getLog(ServicioUsuariosImpl.class);
#Autowired
#Qualifier("servicioEncriptacion")
private ServicioEncriptacion servicioEncriptacion;
#Autowired
#Qualifier("servicioPersistenciaUsuarios")
private ServicioPersistenciaUsuarios servicioPersistenciaUsuarios;
public ServicioUsuariosImpl(){
log.info("Constructor SIN tipo ServicioUsuariosImpl...");
//TODO pendiente cargar el mapa con una llamada al servicioPersistencia
}
#PostConstruct
public void init()
{
log.info("init method on ServicioUsuariosImpl. Initializing hashMap...");
//i need to call persistence layer to fill the hashMap
}
some methods, getters and setters
}
As you can see, this service has inyected a persistent service called servicioPersistenciaUsuarios, which basically uses a dao marked as #repository.
this is ServicioPersistenciaUsuariosImpl implementation file:
package com.aironman.core.service;
**#Service("servicioPersistenciaUsuarios")
public class ServicioPersistenciaUsuariosImpl implements ServicioPersistenciaUsuarios** {
#Autowired
#Qualifier("usuarioHibernateDao")
private UsuarioHibernateDao usuarioHibernateDao;
private Log log = LogFactory.getLog(ServicioPersistenciaUsuariosImpl.class);
public ServicioPersistenciaUsuariosImpl()
{
log.info("Constructor ServicioPersistenciaUsuariosImpl...");
}
some methods, getters and setters
}
this is usuarioHibernateDao implementation file:
package com.aironman.core.hibernate;
**#Repository
public class UsuarioHibernateDao extends HibernateGenericDao<Usuario, String> implements UsuarioDao**
{
private Log log = LogFactory.getLog(UsuarioHibernateDao.class);
[B]#Autowired
public UsuarioHibernateDao(#Qualifier("sessionFactory") SessionFactory sessionFactory) [/B]{
super(sessionFactory);
}
some methods...
}
ServicioUsuariosImpl has another dependencie, servicioEncriptacion, and as you may see, this is the implementation:
package com.aironman.core.service;
#Service("servicioEncriptacion")
public class ServicioEncriptacionImpl implements ServicioEncriptacion
{
private static final String algoritmo = "SHA-256";
private Log log = LogFactory.getLog(ServicioEncriptacionImpl.class);
private static java.security.MessageDigest diggest ;
[B]public ServicioEncriptacionImpl()[/B]
{some code...
}
some methods...
}
this is ServicioItemsImpl implementation file, another dependencie belongs to StoreServiceImpl.
package com.aironman.core.service;
**#Service("servicioItems")
public class ServicioItemsImpl implements ServicioItems**{
private static final ConcurrentHashMap
<String,com.aironman.core.pojos.Item>
//La pk es el isbn del item
hashMapItems = new ConcurrentHashMap<String,com.aironman.core.pojos.Item>() ;
private Log log = LogFactory.getLog(ServicioItemsImpl.class);
#Autowired
#Qualifier("servicioPersistenciaItems")
private ServicioPersistenciaItems servicioPersistenciaItems;
[B]public ServicioItemsImpl()[/B]
{
log.info("Constructor SIN TIPO ServicioItemsImpl");
}
[B]#PostConstruct
public void init()[/B]
{
log.info("init method on ServicioItemsImpl. Initializing hashMap...");
}
some methods, getters and setters
}
this is servicioPersistenciaItems implementation file:
package com.aironman.core.service;
#Service("servicioPersistenciaItems")
public class ServicioPersistenciaItemsImpl implements ServicioPersistenciaItems
{
#Autowired
#Qualifier("itemHibernateDao")
private ItemHibernateDao itemHibernateDao;
private Log log = LogFactory.getLog(ServicioPersistenciaItemsImpl.class);
[B]public ServicioPersistenciaItemsImpl()[/B]
{
log.info("Constructor SIN tipo ServicioPersistenciaItemsImpl...");
}
some methods, getters and setters...
}
and finish, ServicioApuntesContablesImpl implementation file, with no dependencies
package com.aironman.core.service;
[B]#Service("servicioApuntes")
public class ServicioApuntesContablesImpl implements ServicioApuntesContables[/B]{
private Log log = LogFactory.getLog(ServicioApuntesContablesImpl.class);
private static ConcurrentHashMap <ClaveApunteContable,ApunteContable> mapaApuntesContables
= new ConcurrentHashMap <ClaveApunteContable,ApunteContable> ();
//TODO al final tendre que persistir los apuntes contables, por ahora los mantendre en memoria...
[B]public ServicioApuntesContablesImpl()[/B]
{}
some methods
}
in short, the problem is happening when Spring tries to instantiate the endpoint implementation file storeService and do not understand it because I have no typed constructor in any of the files, getters and setters I have the right and above any dependence is used to each other. Can someone please help me and explain what is happening? thank you very much
PD i have not put some code for readability issues and i easyly reach limit caracters, if someone needs to watch, let me know.
Ok, i allready solved my problem. Inside the endpoints.xml file a declared my ws with a id and i d already have declared the implementation ws file with a #Service annotation, so the exception is now clear to me...

Resources