I am trying to learn spring MVC and created a rest service but I am getting bean autowiring problem.
Could not autowire field: taxApp.dao.daoImpl.userDaoImpl taxApp.controller.loginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [taxApp.dao.daoImpl.userDaoImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency
The structure of my spring project looks like
src
main
java
taxApp
controller
loginController.java
model
user.java
dao
daoImpl
userDaoImpl.java
userDAO.java
resources
database
data-source-cfg.xml
user
spring-user.xml
spring-module.xml
webapp
web-inf
dispatcher-servlet.xml
web.xml
index.jsp
Following is how the files looks like
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="taxApp" />
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
spring-user.xml
<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-2.5.xsd">
<bean id="userDAO" class="dao.impl.userDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
spring-module.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Using Oracle datasource -->
<import resource="database/data-source-cfg.xml" />
<import resource="dao/spring-user.xml" />
</beans>
All the other implementation like controller, DAO, service and model look like
loginController.java
#RestController
public class loginController {
#Autowired
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
userDAO.java
public interface userDAO {
public void insert(user _user);
public user findUserByEmail(String email);
}
userDaoImpl.java
public class userDaoImpl implements userDAO{
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
//other methods
}
Mark your daoimpl as
#repository
public class userDaoImpl implements userDAO{}
Autowire interface rather marking an concrete class.
Go with java config for spring application much easier to understand.
Could you change the following:
#RestController
public class loginController {
#Autowired
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
by the following:
#RestController
public class loginController {
#Autowired
#Qualifier("userDAO")
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
and see the result?
u r having one setter injection in the bean u want to autowire u have to do something like this
//Autowired annotation on variable/setters is equivalent to autowire="byType"
#Autowired
private Employee employee;
#Autowired
public void setEmployee(Employee emp){
this.employee=emp;
}
Related
I faced a problem with Spring Framework: #Autowired are null, but Spring doesn't throw any exceptions, and I can't understand, why are these fields null.
I have a class:
package com.processing.gates;
public class Main {
private final ApplicationContext context = Context.getContext();
#Autowired private PaymentGateFactory paymentGateFactory;
#Autowired private CalculatorChooser calculatorChooser;
//...
}
And for example I have the following class:
package com.processing.gates.comission;
#Component
public class CalculatorChooser {
//...
}
Here is my Spring configuration xml:
<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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.processing.gates"/>
<bean id="logPath" class="java.lang.String"> <!-- путь к папке с логами -->
<constructor-arg value="/home/yoba/NetBeansProjects/processing/gates/log/"/>
</bean>
<!-- ... -->
</beans>
When I try to write in xml:
<bean id="calculator" class="com.processing.gates.comission.CalculatorChooser"/>
and get it from code:
CalculatorChooser cc = (CalculatorChooser)Context.getContext().getBean("calculator");
it works fine. But #Autowired doesn't work. How can I fix this? Thanks!
Let Spring manage the bean by either declaring a Main bean in the application context file or by using the #Component annotation as you've already done for CalculatorChooser
<bean id="mainBean" class="com.processing.gates.Main"/>
I autowired some beans from my testConfig.xml, and it works fine but when I want to autowire a properties file it gives null, the properties file is near of my xml in selenium folder. My testConfig.xml 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:util="http://www.springframework.org/schema/util"
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-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd" >
<bean id="base" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite" />
</bean>
<bean id="siteBase" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite/site" />
</bean>
<bean id="adminBase" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite/admin" />
</bean>
<bean id="firefoxDriver" class="org.openqa.selenium.firefox.FirefoxDriver" destroy-method="quit"/>
<context:annotation-config/>
<util:properties id="seleniumSelectors" location="classpath:selenium/selenium-selectors.properties"/>
</beans>
and here I want to autowire it:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/testConfig.xml" })
public abstract class AbstractUITest extends TestCase{
#Autowired
protected URI base;
#Autowired
protected URI siteBase;
#Autowired
protected URI adminBase;
#Autowired
protected WebDriver firefoxDriver;
#Autowired
#Qualifier("seleniumSelectors")
protected Properties selectors;
protected By getBySelectorKey(String key){
if(key.endsWith(".xpath")){
return By.xpath(selenium.getProperty(key));
}
}
Just the selectors object is null and I don`t know why, any suggest?
UPDATE 2:
I made a mistake everithing is null when the selector is null.I cheked Initialization in my test runs before autowired, somehow this
public class AdminCandidatesPageUITest extends AbstractAdminUITest {
private By COMPONENT_QUERY_TEXTBOX_EMAIL = getBySelectorKey("admin.candidates.edit.textbox.email.xpath");
private By COMPONENT_QUERY_TEXTBOX_EMAIL_ERROR = getBySelectorKey("admin.candidates.edit.textbox.email.errors.xpath");
should run after seleniumSelector is autowired. Any suggest?
Try to move tag <context:annotation-config/> one line down. I am not sure but it seems that wiring triggered by this tag happens before creating of seleniumSelectors, so it is still null at the moment.
BTW if you mark your properties as #Required the context will fail to start and throw exception because one of the properties is not wired. This is probably preferable than failing later at runtime.
I am attempting to create rest web services to handle CRUD operations for an android application. I'm using Spring 4.0 with Hibernate. I'm trying to autowire a dao and it's always null and I haven't been able to figure out the cause of the issue. I searched online and everything looks right to me so I'm at a complete lost. I defined the bean in the applicationContext as I have saw in many tutorials but I'm unable to get the dao to autowire. Any help would be appreciated.
dispatch-servlet.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.bike.party.services, com.bike.party.daos" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="propertyConfigurer" p:location="/WEB-INF/jdbc.properties"/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource" p:driverClassName="${jdbc.driverClassName}" p:password="${jdbc.password}" p:url="${jdbc.url}" p:username="${jdbc.username}"/>
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.bike.party.models"/>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager" p:sessionFactory-ref="sessionFactory" />
<tx:annotation-driven/>
</beans>
UserDao
package com.bike.party.daos;
import com.bike.party.models.User;
public interface UserDao extends Dao<User> {
public User findByUserName(String username);
}
UserDaoImpl
package com.bike.party.daos;
import com.bike.party.models.User;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
#Repository
#Transactional
#Qualifier("userDaoImpl")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public User findByUserName(String username) {
List<User> userList = sessionFactory.getCurrentSession().createCriteria(User.class).add(Restrictions.eq("username", username)).setMaxResults(1).list();
return userList.isEmpty() ? null : userList.get(0);
}
}
UserWebService
package com.bike.party.services;
import com.bike.party.daos.UserDao;
import com.bike.party.models.User;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Provider
#Component
#Path("userservice")
public class UserWebService {
#Autowired
private UserDao userDao;
#GET
#Path("/user/{username}")
#Produces(MediaType.TEXT_PLAIN)
public String getUser(String username) {
if (userDao == null) {
return "the dao is null";
}
User user = userDao.findByUserName(username);
if (user == null) {
return "No user was found.";
} else {
return user.getUsername();
}
}
}
UPDATE:
I modified the UserWebService with
private UserDao userDao;
#Autowired
public void setUserDao(UserDao userDao) {
if (functionDao != null) {
System.out.println(String.valueOf(userDao.findByUserName("chris")));
} else {
System.out.println("setting the dao is null :(");
}
this.userDao= userDao;
}
When the web app is deployed this is called and finds the user but when I call it from the client it is always null. Could this be because I'm calling the service directly and not going through spring? If so could any point me to the create way to call the service from the client. Thanks
i believe spring can not find your UserDao class.
try to change your component-scan instruction in dispatch-servlet.xml to this one:
<context:component-scan base-package="com.bike.party.*" />
If you're using Spring Tool Suite all #Component's in your project should be marked as Component(icon with S):
EDIT:
remove bean definition from xml, do not mix xml and annotated configuration.
Remove also "userDaoImpl" from your Annotations. Change #Repository("userDaoImpl") to #Repository()
Remove the <bean id="userDao" class="com.bike.party.daos.UserDaoImpl" /> bean from the applicationContext.xml file.
I think you are injecting this instance instead of the the one that gets created via the #Repository annotation which is why your SessionFactory is null
Try to derive your UserWebService from SpringBeanAutowiringSupport.
I have a Spring controller that I think is getting instantiated more than once based on the object ids I see when I debug through the code.
Controller:
#Controller
#RequestMapping("/services/user")
public class UserController{
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
#RequestMapping(method = RequestMethod.POST, value = "/createUser")
public #ResponseBody String createUser(#RequestBody User user) throws UserNotCreatedException {
try {
userService.createUser(user);
return user.getEmail();
} catch (Exception e) {
e.printStackTrace();
throw new UserNotCreatedException("User not created");
}
}
Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Scans the classpath of this application for #Components to deploy as
beans -->
<context:component-scan base-package="com.xyz.controller" />
<context:annotation-config />
<bean id="userController" class="com.xyz.UserController">
<property name="userService" ref="userService" />
</bean>
<bean id="userService" class="com.xyz.UserServiceImpl">
<property name="userDao" ref="userDaoMysql" />
</bean>
<bean id="userDaoMysql" class="com.xyz.UserDaoImpl" >
<property name="dataSource" ref="dataSource"></property>
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
I noticed the problem when I realized that userService is null when I make a request that goes through UserController. However; when I put break points, I see that userService does get set in another instance of UserController.
The other comments in this thread did not take into account the package of the UserController class. The supplied Spring config initializes component-scanning on com.xyz.controller as the base package. The UserController class looks like it is outside of this in com.xyz and thus would not be picked up by component-scanning (unless that is a typo #user269091 - which could be your problem!).
I should note that I don't understand why your controller would not be in your controller package. It would be cleanest to move the controller there, add #Autowired above the line private UserService userService; and remove the manual UserController definition in the Spring config, so that the component-scanning just picks up your bean automatically and wires up the UserService.
With that being said, I really don't see why there would be a problem with what you have shown. Do you have new UserController() anywhere in your code? Is there any other Spring configuration?
To build on #adashr's answer
If you remove the manual configuration, then you're now initializing things based on annotations. The #Controller annotation will correctly create the Controller, but nothing wires in the UserService now
You need a #Autowired for the UserService to instantiate it since your spring config is now annotation driven
You are mixing annotations and bean xml configuration.
If you are using #Controller annotaion, you do not need to define the controller bean in XML.
The instruction
<context:component-scan base-package="com.xyz.controller" />
takes care of registering the controller bean for you (your controller bean is inside that package).
I suggest you to use mvc namespace while configuring Spring MVC to keep configuration minimal and more readable.
Hi,
I am using spring 3.0 with Quartz in a scheduler class. I have created the application context by
private static final ClassPathXmlApplicationContext applicationContext;
static {
applicationContext = new
ClassPathXmlApplicationContext("config/applicationContext.xml");
}
The problem is that none of the #Autowired beans actually get auto-wired, so I have to manually set dependencies like this:
<bean class="com.spr.service.RegistrationServiceImpl" id="registrationService">
<property name="userService" ref="userService" />
</bean>
Example of where I'm using #Autowired:
public class RegistrationService {
#AutoWired private UserService userService;
// setter for userService;
}
public class UserService{
// methods
}
I also made sure to enable the annotation configuration in my Spring config:
<context:annotation-config/>
<bean id="registrationSevice" class="RegistrationService"/>
<bean id="userService" class="UserService"/>
Why is #Autowired not working for me?
You haven't provided the UserService class source code so I can't be sure about your problem. Looks like the UserService class is missing a 'stereotype' annotation like #Component or #Service. You also have to configure the Spring classpath scanning using the following 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"
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">
<!-- Add your classes base package here -->
<context:component-scan base-package="your.package"/>
</beans>
Your beans must include one of the Spring stereotype annotations like:
package your.package;
#Service
public class UserService{
}
Atlast i got it resolved by adding the
<context:component-scan base-package="your.package"/>
in my applicationContext.xml. Thank u all for your support.