component-scan not finding #Repository - java

My classes look like this:
AbstractDAO
package dao.impl;
public abstract class AbstractDAO <E> implements DAO<E> {
#PersistenceContext
private EntityManager em;
public void add(E entity) {
em.persist(entity);
}
}
DAOImpl
package dao.impl;
#Transactional
#Repository
public class ItemDAOImpl extends AbstractDAO<Item> {
}
application-context-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: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-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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="dao.impl" />
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="domain" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.archive.autodetection">class</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/inventory" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven />
TEST class
package service.impl;
#ContextConfiguration(locations = "classpath:application-context-test.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class ItemTest {
#Autowired
private ItemDAOImpl itemDAO;
#Test
public void testCreateItem() throws Exception {
Item item = new Item("cellphone", "galaxy", ItemType.TECHNOLOGY, 10000);
itemDAO.add(item);
assertEquals(5, itemDAO.list(Item.class).size());
}
}
Should not this code be able to autowire my itemDAO?
When I run my test it throws an exception saying
org.springframework.beans.factory.BeanCreationException: Could not autowire
field: private dao.impl.ItemDAOImpl service.impl.ItemTest.itemDAO; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [dao.impl.ItemDAOImpl] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations:
Could you please tell what am I missing? The only thing I can think about is that since my test is in src/test/java, my application-context-test.xml is in src/test/resources and my dao is in src/main/java. Maybe the component-scan scanning in the wrong place?

Because ItemDAOImpl is annotated with #Transactional, spring will create a proxy for this bean and inject the proxy, not the bean itself when autowiring.
Spring can create proxies by subclassing (using Cglib) or by implementing the beans interfaces with Jdk proxies.
Which type of proxy spring uses, depends on your configuration.
I had similar problems as you described and the cause was, that spring used Jdk proxies and I wasnt aware of it.
In your case the spring bean for ItemDaoImpl would be a proxy implementing DAO.
This cannot be injected into
#Autowired
private ItemDAOImpl itemDAO;
because it cannot be cast to ItemDaoImpl.
That would explain the exception you are facing.
To fix that, change the field to
#Autowired
private DAO<Item> itemDAO;
The above only works, if you are using spring 4.
With earlier versions of spring you have to create an interface
public interface ItemDAO extends DAO<Item>
and let ItemDaoImpl implement it.
Finally change your field where you want it to be injected to
#Autowired
private ItemDAO itemDAO;

Related

Annotation not working in spring

i am a beginner in spring ,i have a dao class in spring .but annotation # auto wired or # service is not working ,i have solved the issue by creating a bean in application context,what is the reason for annotation not working in spring .provided with "context:component-scan base-package=" also but annotations are not working
StudentDao
public interface StudentDao {
public int addStudent(StudentEntity s);
}
-----------------------------------
#Service("studentDaoImpl")
public class StudentDaoImpl implements StudentDao{
#PersistenceContext
private EntityManager em;
#Override
#Transactional
public int addStudent(StudentEntity student) {
// TODO Auto-generated method stub
em.persist(student);
return student.getId();
}
}
------------------------------------------------
FascadeDaoImpl
public class FascadeControllerImpl implements FascadeController {
// #Autowired
private StudentDao studentDao;
private UserContext uc;
public void studentDao() {
studentDao=(StudentDao) uc.getContext().getBean("studentDao");
}
}
public int addStudent(StudentEntity student) {
studentDao();
return studentDao.addStudent(student);
}
ApplicationContext
<?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: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/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="sms.spring.dao" />
<context:component-scan base-package="sms.spring.fascade" />
<context:component-scan base-package="sms.spring.entity" />
<context:annotation-config />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean class="sms.spring.entity.StudentEntity" id="studentbean"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value>
</property>
<property name="url">
<value>jdbc:sqlserver://localhost;databaseName=dbstsms</value>
</property>
<property name="username">
<value>sa</value>
</property>
<property name="password">
<value>sa123</value>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="PERSUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="fascadeController" class="sms.spring.fascade.FascadeControllerImpl"></bean>
<bean id="studentDao" class="sms.spring.dao.StudentDaoImpl"></bean>
<bean id="loginDao" class="sms.spring.dao.LoginDaoImpl"></bean>
<bean id="facultyDao" class="sms.spring.dao.FacultyDaoImpl"></bean>
<bean id="markDao" class="sms.spring.dao.MarkDaoImpl"></bean>
<bean id="notificationDao" class="sms.spring.dao.NotificationDaoImpl"></bean>
<tx:annotation-driven />
Please post the error that you are getting,Also from the code you have posted I can see that even though you have annotated the StudentDaoImpl class with #service annotation you are again defining the same in the xml configuration,Kindly use either annotation based config or xml based configuration.
Please check if your file has
<context:annotation-config/> is mentioned in the xml config(Not needed if component scan is enabled)
Check if component scan is enabled for the package
Please refer to this answer for the correct schema location
Question is not clear, but it looks like your controller should also be annotated with #Controller. All classes belonging to a Spring project that have autowired dependencies, need to be created by Spring. In short, you should never make a new of a Spring class and create them using the ApplicationContext#getBean() or when it gets injected by another class.
Moreover, bear in mind with the constructors as at the point of creation of the bean the autowired dependencies are null (not initialized) and you need to create an init() method annotated with #PostConstruct.
Two main causes are:
You must tell spring, where to scan your components (make sure the packages are right)
You don't have an implementation of an actual bean (make sure StudentDao have #Service too)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed

I have browsed many related topics and tried different ways, but the error is still there. Environment: Spring data jpa, Hibernate, maven, tomcat7
Error Stack:
org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zzz.service.UserService com.zzz.controller.UserController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.zzz.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)}
at
...
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" ... ... >
<context:component-scan base-package="com.zzz">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/zzz" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="com.zzz.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<jpa:repositories base-package="com.zzz.repository" />
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" ... ... >
<context:component-scan base-package="com.zzz.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="static/" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/defs/templates.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
</beans>
UserController.java
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("/users")
public String users(Model model) {
model.addAttribute("users", userService.findAll());
return "users";
}
}
UserService.java
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
}
UserRepository.java
public interface UserRepository extends JpaRepository<User, Integer> {
}
UDPATE 1
There are 2 autowired errors:
Could not autowire field: private com.zzz.repository.UserRepository com.zzz.service.UserService.userRepository
could not autowire field: private com.zzz.service.UserService com.zzz.controller.UserController.userService
UPDATE 2
I've tried to use servlet-dispatcher.xml as the only configuration file (put the content of applicationContext.xml into it), it works fine. So it's the problem between these 2 xml files, but I couldn't tell it.
UPDATE 3
I renamed applicationContext.xml to root-context.xml, and set the contextConfigLocation to it in web.xml, the error disappeared!
It seems to be some configuration error about the applicationContext.xml, anybody could help?
another guess: in the dispatcher xml you only scan for the controller package...so if the application.xml is not loaded it does not scan the service package and thus the user service is not loaded... would be interesting what happens if you scan for the entire com.zzz package in the dispatcher.xml

Spring 4 and Hibernate 4/c3p0 with Entity Manager don't start

I create the configuration of Spring + JPA/Hibernate/c3p0 on this way:
Spring-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.nassoft.erpweb"/>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<mvc:annotation-driven />
<mvc:interceptors>
<bean class="com.nassoft.erpweb.login.interceptor.AuthenticatorInterceptor" />
</mvc:interceptors>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.nassoft.erpweb.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/nsm_erp" />
<property name="user" value="root" />
<property name="password" value="1234" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxStatements" value="50" />
<property name="idleConnectionTestPeriod" value="3000" />
<property name="loginTimeout" value="300" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
I'm not using persistence.xml because I read in some places its not necessary in Spring 4 with Hibernate.
When I start the server it still loading and don't start in 45s (nor 180s) in Tomcat7.
I create a factory of EntityManager to use in my project:
package com.nassoft.erpweb.factory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
public class ConnectionFactory {
#PersistenceUnit
private static EntityManagerFactory entityManagerFactory;
public static EntityManager getEntityManager(){
if (entityManagerFactory == null){
entityManagerFactory = Persistence.createEntityManagerFactory("ERPWeb");
}
return entityManagerFactory.createEntityManager();
}
}
I think my configuration is not correct, but I don't found any places with a good text about it.
Can someone help-me?
Edited.
Problem solved!
First: I applied Dependency Injection in each controller to bring the DAOs with IoC.
Second: I use the annotation #Repository to create a repository in each DAO that will receive my databases methods.
Third: I created the EntityManage in this way for each DAO:
#PersistenceContext
private EntityManager manager;
This is not a complete answer. I"m just pointing you to a direction.
Spring cannot find the ConnectionFactory class of yours, so it will not inject the entityManagerFactory. Its not required for you to again create a singleton for passing the entityManager, so no ConnectionFactory class is required. Spring will do it for you by injecting into the DAO or Controller etc., for example you have the following DAO that gets the data.
#Service
public class SomeDAO {
#AutoWire -- i'm not sure what you call for the entityManager.
private static EntityManagerFactory entityManagerFactory;
}
There is more info here. Instead of #autowiring he is using manual injection. I your case ,you can try with autowiring.
Also make sure that you have these classes in the <spring:component-scan /> path of the application context file or else the spring wont be able to recognize and inject the entity manager.

Adding TransactionManager in Hibernate Spring

Getting error when adding Transaction-Manager. What's wrong? :/
Few possible answers reffer to lack of some hibernate libraries. However It seems that all of them do persist. How to overcome this?
Also I want to add some test data to my database. In what class is it better to insert it?
Thank you.
ERROR:
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception
parsing XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested
exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Dispatcher-Servlet:
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-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/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">
<context:annotation-config />
<context:component-scan base-package="miniVLE.controller" />
<context:component-scan base-package="miniVLE.service" />
<context:component-scan base-package="miniVLE.beans" />
<context:component-scan base-package="miniVLE.dao" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<!-- Declare a view resolver-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!-- Connects to the database based on the jdbc properties information-->
<bean id="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name ="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name ="url" value="jdbc:derby://localhost:1527/minivledb"/>
<property name ="username" value="root"/>
<property name ="password" value="123" />
</bean>
<!-- Declares hibernate object -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> ${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<!-- A list of all the annotated bean files, which are mapped with database tables-->
<property name="annotatedClasses">
<list>
<value> miniVLE.beans.Course </value>
<value> miniVLE.beans.Student </value>
<value> miniVLE.beans.Department </value>
<value> miniVLE.beans.Module </value>
<value> miniVLE.beans.TimeSlot </value>
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
DAO:
#Repository
public class MiniVLEDAOImplementation implements MiniVLEDAO{
// Used for communicating with the database
#Autowired
private SessionFactory sessionFactory;
#Override
public void addStudentToDB(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}....
Service:
#Service
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class StudentService implements IStudentService{
#Autowired
MiniVLEDAOImplementation dao;
public StudentService() {
System.out.println("*** StudentService instantiated");
}
#Override
public Student getStudent(String urn){
Student s = dao.getStudentFromDB(urn);
return s;
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addStudent(Student student) {
dao.addStudentToDB(student);
}...
Controller:
#Controller
public class miniVLEController {
#Autowired
StudentService studentService;
After adding the aopalliance-1.0.jar getting next
ERROR:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.service.StudentService miniVLE.controller.miniVLEController.studentService; nested exception is java.lang.IllegalArgumentException: Can not set miniVLE.service.StudentService field miniVLE.controller.miniVLEController.studentService to sun.proxy.$Proxy536
One of the solutions was to add <aop:aspectj-autoproxy proxy-target-class="true"/>into the dispatcher-servlet.
next Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController' defined in file
[C:\Users\1\Documents\NetBeansProjects\com3014_mini_VLE\build\web\WEB-
INF\classes\miniVLE\controller\miniVLEController.class]: BeanPostProcessor before
instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError:
org/aspectj/lang/annotation/Aspect
You need to add aopalliance.jar dependency.
If you use maven:
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
Following the problem escalation:
Needed to find aspectjrt-1.x.x.jar that was missing to overcome last error and then to overcome org.aspectj.util.PartialOrder.PartialComparable error you need to get aspectjtools-1.X.X.jar
here I found all extra libraries i needed
http://www.jarfinder.com/index.php/java/info/org.aspectj.lang.NoAspectBoundException

spring-nullpointerexception- cant access autowired annotated service (or dao) in a no-annotations class

I have this problem that I cannot fix.
From my #Controller, i can easily access my autowired #Service class and play with it no problem.
But when I do that from a separate class without annotations, it gives me a NullPointerException.
My Controller (works)-
#Controller
public class UserController {
#Autowired
UserService userService;...
My separate Java class (not working)-
public final class UsersManagementUtil {
#Autowired
UserService userService;
or
#Autowired
UserDao userDao;
userService or userDao are always null!
Was just trying if any one of them works.
My component scan setting has the root level package set for scanning so that should be OK.
my servlet context -
<?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"
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">
<!-- the application context definition for the
springapp DispatcherServlet -->
<!-- Enable annotation driven controllers, validation etc... -->
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="x" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<!-- package shortended -->
<bean id="messageSource"
class="o.s.c.s.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</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>
<!-- package shortened -->
<bean id="viewResolver"
class="o.s.w.s.v.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
<property name="order">
<value>0</value>
</property>
</bean>
<!-- package shortened -->
<bean id="sessionFactory"
class="o.s.o.h3.a.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>orion.core.models.Question</value>
<value>orion.core.models.User</value>
<value>orion.core.models.Space</value>
<value>orion.core.models.UserSkill</value>
<value>orion.core.models.Question</value>
<value>orion.core.models.Rating</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Any clue?
From Spring Reference 3.0
By default, classes annotated with
#Component, #Repository, #Service,
#Controller, or a custom annotation
that itself is annotated with
#Component are the only detected
candidate components.
UsersManagementUtil should be annotated with one of them based on your need.
Spring dependency injection works only in components managed by Spring. If your UsersManagementUtil is not managed by Spring (i.e. is not a Spring bean), #Autowired doesn't work inside it. Either declare it as a Spring bean (using <bean> or annotation), or trigger autowiring manually after instantiation of the object using
applicationContext.getAutowireCapableBeanFactory().autowireBean(object);

Categories

Resources