@Autowired not working in Spring restful web service

I am developing application using Struts2 + Spring4 + Hibernate4 with RESTful web service. I have configured Hibernate in Spring bean file. For RESTful web service I have excluded URL in struts.xml using

<constant name="struts.action.excludePattern" value="/service/.*"/> 

If I access sessionFactory object in any action class it works fine. But if I access it in my web service it gives NullPointerException.

After searching on Google I found that if we bypass URL from Struts it does not allow to initialize object using @Autowired annotation.

How to sort out this thing? I have searched on Google but nothing useful found.

This is my service:

public class AccountServiceImpl implements AccountService {
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;

    public Response getAllAccounts() {
         Session session = this.sessionFactory.getCurrentSession();
         List<VbarAccount> personList = session.createQuery("from TEST").list();
         return Response.status(200).build();


This is my bean mapping:

<bean id="accountService" class="com.xxx.yyy.services.impl.AccountServiceImpl">
    <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />


Autowired works if you get the object from Spring, and the object should be configured as a Spring bean before you get it from the context. To configure some class as a Spring bean sometimes only needed to put some @Component annotation and ensure that the class is scanned for annotations. In you case a @Service annotation is more appropriate

public class AccountServiceImpl implements AccountService { 

In the applicationContext.xml you should have

<context:component-scan base-package="com.xxx.yyy.services"/>

Leave a Reply

Your email address will not be published. Required fields are marked *