#Qualifier annotation not working - spring

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>

Related

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.

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.

Spring Autowiring not working - BeanCreationException

I want to integrate Spring with Hibernate. I am new to both technologies. At the moment I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public service.UserService controller.HomeController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.UserService] 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)}
Can anybody help me, please?
package controller;
#Controller
public class HomeController {
#Autowired
private UserService userService;
#RequestMapping("/register")
public ModelAndView getRegisterForm(#ModelAttribute("user") User user,
BindingResult result) {
ArrayList<String> gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");
ArrayList<String> city = new ArrayList<String>();
city.add("Delhi");
city.add("Kolkata");
city.add("Chennai");
city.add("Bangalore");
Map<String, Object> model = new HashMap<String, Object>();
model.put("gender", gender);
model.put("city", city);
System.out.println("Register Form");
return new ModelAndView("Register", "model", model);
}
#RequestMapping("/saveUser")
public ModelAndView saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
System.out.println("Save User Data");
return new ModelAndView("redirect:/userList.html");
}
#RequestMapping("/userList")
public ModelAndView getUserList() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", userService.getUser());
return new ModelAndView("UserDetails", model);
}
}
package service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDao userDao;
#Override
public void addUser(User user) {
userDao.saveUser(user);
}
#Override
public List<User> getUser() {
return userDao.getUser();
}
}
spring-servlet Code:
Hi need a Spring ,Hibernate integration example for my new project.so i have copied this from a website.and i did some modifications in that ..It's not working please help me
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="controller" />
<tx:annotation-driven/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="myydao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="/user/*.htm" class="controller.HomeController" >
<property name="UserDao" ref="mydao" />
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I assume that you haven't added the bean to your Spring Application Context
If you are using xml, you need to do this by adding something like the following to the xml file:
<bean class="service.UserServiceImpl" id="userService"/>
Or, if you are using a Java based configuration class, you need to add a bean like so:
#Configuration
public class AppConfig{
#Bean
public UserService userService() {
return new UserServiceImpl();
}
}
Or, if you add the #Component annotation to UserServiceImpl and #ComponentScan("service") annotation to the Java App config, it should pick up the User service
Make sure you have enabled the component scanning to automatically detect classes and register respective beans.
You should add below entry to your bean definition XML file:
<context:component-scan base-package="org.example"/>
More about automatic bean detection

Spring Autowire JdbcDaoSupport

I'm receiving the an error when trying to autowire a class that extends JdbcDaoSupport. I have my DAO classes and Controller classes separated into 2 different spring contexts. DAO classes are in the root context and the Controller classes are in the servlet context. I've set up the component-scanning so that there is no overlap in beans between the 2 contexts (is that the correct pattern?). All these factors combined with the fact that my DAOs extend JdbcDaoSupport seems to be causing the issue, and I don't understand why. I'm just learning spring so I don't fully understand all the concepts yet.
EDIT: This behavior seems to be caused by the fact that JdbcDaoSupport/DaoSupport implements the InitializingBean interface. Still confused though.
Here is the error I am receiving:
Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.test.dao.CustomerDAO2 org.test.servlet.HomeController.customerDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.test.dao.CustomerDAO2] 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)}
Here are my files:
HomeController.java
package org.test.servlet;
import java.util.Locale;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.test.dao.*;
#Controller
public class HomeController
{
#Autowired
CustomerDAO2 customerDAO;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
model.addAttribute("customer", customerDAO.getCustomer());
return "home";
}
}
CustomerDAO2.java
package org.test.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.*;
import org.test.dto.Customer;
#Repository
public class CustomerDAO2 extends JdbcDaoSupport
{
public CustomerDAO2()
{
}
#Autowired
public CustomerDAO2(DataSource datasource)
{
this.setDataSource(datasource);
}
#Transactional
public Customer getCustomer()
{
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
Customer customer = jdbcTemplate.queryForObject("select * from customer", new CustomerMapper());
return customer;
}
public static class CustomerMapper implements RowMapper<Customer>
{
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException
{
Customer customer = new Customer();
customer.setCustomerId(rs.getInt("customerId"));
customer.setCustomerNumber(rs.getString("customerNumber"));
return customer;
}
}
}
application-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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="org.test">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<!-- Enables the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/crm?user=root&password=password" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
servlet-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="org.test.servlet"/>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I found my answer in this post:
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
Basically, I need to create an interface for my DAO classes. Something like this:
public interface ICustomerDAO {
Customer getCustomer();
}
Note: it would probably be better to make a more generic CRUD interface.
Then you use the interface type for dependency injection instead of using the class type:
#Autowired
ICustomerDAO customerDAO;
The reason this is necessary is because Spring creates underlying proxy classes:
http://insufficientinformation.blogspot.com/2007/12/spring-dynamic-proxies-vs-cglib-proxies.html
http://docs.spring.io/spring/docs/2.5.x/reference/aop.html#aop-proxying

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