1

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


I am trying to autowire a private field in my service class using this tutorial. My problem is that restaurantOwnerRepository remains null and does not get initialized.

servlet-context.xml

<context:component-scan base-package="com.mahlzeit.web.server" />

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>

<tx:annotation-driven />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="restaurantOwnerRepository" class="com.mahlzeit.web.server.dao.RestaurantOwnerRepository">
    <constructor-arg>
        <ref bean="sessionFactory" />
    </constructor-arg>
</bean>  

Service code:

@Component
public class RestaurantInformationServiceImpl  extends XsrfProtectedServiceServlet implements RestaurantInformationService {
    private static final long serialVersionUID = -4088840947018614411L;

    @Autowired
    private RestaurantOwnerRepository restaurantOwnerRepository;

    private final static Logger logger = Logger.getLogger(RestaurantInformationServiceImpl.class);

    @Override
    public List<RestaurantDTO> getAvailableRestaurants() {

        // restaurantOwnerRepository is 'null'
        List<Restaurant> availableRestaurants = restaurantOwnerRepository.getAvailableRestaurants(getSessionId());

        return null;
    }

    private String getSessionId() {
        HttpServletRequest httpRequest = getThreadLocalRequest();
        return httpRequest.getSession().getId();
    }
}

RestaurantOwnerRepository.java

public class RestaurantOwnerRepository implements RestauranOwnerDAO {

    private SessionFactory sessionFactory;

    public RestaurantOwnerRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // ..
}

What could be the reason for this?

Community
  • 1
  • 1
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • Because first it isn't a component so will have nothing injected. You have `@Configurable` which requires an aspect and either load or compile timeweaving both of which aren't available in your configuration. Hence it will remain null. – M. Deinum Jul 23 '15 at 08:52
  • Also it appears to be a servlet and not a service so if you have defined it as a servlet injection will never happen if you haven't setup `@Configurable` correctly. – M. Deinum Jul 23 '15 at 08:56
  • well you are trying to autowire a bean , in a servlet which is not managed bean , instead at start up it loads the spring environment to be mapped for the chain process. Try do this example , because it will try to load a managed bean after the context has been loaded http://stackoverflow.com/questions/6414373/load-spring-bean-into-a-servlet – AntJavaDev Jul 23 '15 at 09:15
  • @AntJavaDev Does that mean that I'd have to load all beans "*by hand*"? Is that something I want? That means I'd have to have a `private ApplicationContext context` in each servlet to load my beans, right? – Stefan Falk Jul 24 '15 at 16:32
  • yes like that , in order to make the servlet manageable you ll have to make it contextAware at the startup , but still you will need to inject the ServiceBeans by hand , and also , why you need to autowire a DAO service in the servlet ? arent you using the Spring MVC? – AntJavaDev Jul 26 '15 at 20:05
  • @AntJavaDev I'm pretty new to Spring and all its features.. Until now I was just using Hibernate and GWT (Google Web Toolkit). Right now I am trying to let Spring handle the Hibernate sessions for me on the server side. Regarding the DAO service .. I'm trying to make it run like it's described in [this tutorial](http://www.codejava.net/frameworks/spring/spring-4-and-hibernate-4-integration-tutorial-part-1-xml-configuration) - I am not sure if that's the best way. – Stefan Falk Jul 27 '15 at 10:11
  • yes the example you shared is using spring MVC and hasn't implement a custom dispatcher instead of your example where you try to perform the operations in the dispatcher , try follow this approach , it should operate properly. – AntJavaDev Jul 27 '15 at 10:18
  • @AntJavaDev Alright, thank you! Do you want to provide an answer for my question here? Or should I delete it? I was following the steps from you link http://stackoverflow.com/questions/6414373/load-spring-bean-into-a-servlet – Stefan Falk Jul 27 '15 at 10:29
  • @AntJavaDev Am I getting this wrong..? The tutorial is autowiring `@Autowired private UserDAO userDao;` like I am autowiring `@Autowired private RestaurantOwnerRepository restaurantOwnerRepository;`. Imho I am doing the same as the tutorial. – Stefan Falk Jul 27 '15 at 10:50
  • no you are not doing the same , if you check the bean that his autowiring the dao in the tutorial , is a spring managed bean (Controller) , in your example you are preparing 2 classes of the servlet , the one is a managed bean which will never be used and the second is the actual servlet that the server uses , which do not know any context thus the dao is null , i will provide the answer with the correct controller – AntJavaDev Jul 27 '15 at 11:20
  • @AntJavaDev Oh I think I'm getting the issue now. According to [this](http://stackoverflow.com/questions/13714018/spring-gwt-or-spring-vs-gwt) I won't really need the Spring MVC part of Spring. Thank you! – Stefan Falk Jul 27 '15 at 11:29
  • ye still you can implement the controller in order to send the data in JSON form with restful calls from GWT to the server side and the opposite – AntJavaDev Jul 27 '15 at 11:40

1 Answers1

0

here is a sample controller for your example , you should define the bean in your context.xml or if you place it in this package : com.mahlzeit.web.server it will be managed by spring automatically , cause as i see you have placed the context:component-scan

@Controller
public class RestaurantInformationServiceImpl  {

    @Autowired
    private RestaurantOwnerRepository restaurantOwnerRepository;

    @RequestMapping(value="/")
    public @ResponseBody ModelAndView getRestaurants( 
    HttpServletRequest request, 
    HttpServletResponse response) { 
            ModelAndView model = new ModelAndView("yourPage");
            List<?> rests = restaurantOwnerRepository.getAvailableRestaurants(httpRequest.getSession().getId());
            model.addObject("restList", rests );
            return model;
        }

}
AntJavaDev
  • 1,204
  • 1
  • 18
  • 24