@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:

@Path("service/account-management")
public class AccountServiceImpl implements AccountService {
    
    @Autowired
    private SessionFactory sessionFactory;
     
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @POST
    @PermitAll
    @Path("/accounts")
    public Response getAllAccounts() {
        System.out.println(sessionFactory);
         Session session = this.sessionFactory.getCurrentSession();
         List<VbarAccount> personList = session.createQuery("from TEST").list();
         System.out.println(personList);
         session.close();
         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" />
</bean>

Answer

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

@Service
@Path("service/account-management")
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 *