jeudi 30 juin 2016

Why is my Spring @Autowired field returns null?

This is not a duplicate of this question. So please don't close it for "is duplicate of" reasons..


I'm trying to autowire a bean into the java class. My problem is that playerDAO remains null and does not get initialized.

mvc-dispatcher-service.xml

<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"
       xsi:schemaLocation="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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="ngdemo"/>

    <mvc:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>    
</beans>

PlayerDAO.java

@Repository
@SuppressWarnings({"unchecked", "rawtypes"})
public class PlayerDAO {
    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public Player getPlayerByUsername(String username) {
      //some code
    }
}

LoginRestService.java

@Path("/v1")
@Controller
public class LoginRestService {

    @Autowired
    private PlayerDAO playerDAO;

    @Path("/login")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username,
                                     @FormParam("password") String password, @Context UriInfo request) {
     playerDAO.getPlayerByUsername(username);
     //NPE, playerDAO here is null when I'm trying to access it
    }    
}

What am I missing?

Full code available here: https://github.com/Ferenus/hestalis

Aucun commentaire:

Enregistrer un commentaire