0

I'm using my repository in several controllers as well as in my junit test classes successfully. However in a pojo classe (DataInitializer) which should serve as a seed data initializer the autowiring fails. I tried annotating the pojo class with component, service and even controller to no avail. I even have something similar in another project which works just fine (without any annotations). Anyone got a clue about where I go wrong?

The complete stacktrace is as follows as below. And line 38 in DataInitializer.java contains: "Canteen c = canteenRepository.save(canteen);"

java.lang.NullPointerException
    at dk.fitfit.campusfood.config.DataInitializer.initialize(DataInitializer.java:38)
    at dk.fitfit.campusfood.config.ApplicationConfig.<init>(ApplicationConfig.java:17)
    at dk.fitfit.campusfood.config.ApplicationConfig$$EnhancerBySpringCGLIB$$9fe015e9.<init>(<generated>)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

DataInitializer.java

package dk.fitfit.campusfood.config;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import dk.fitfit.campusfood.model.Canteen;
import dk.fitfit.campusfood.model.Course;
import dk.fitfit.campusfood.repository.CanteenRepository;


public class DataInitializer {

    @Autowired
    private CanteenRepository canteenRepository;

    public DataInitializer() {
    }

    public void initialize()
    {
        String name = "Kantinen i something";
        String address = "Somewhere 4";
        String openingHours = "Mandag til torsdag 8:00 - 15:00. Fredag 8:00 - 14:30\nMorgenmad 8:00 - 9:30\nFrokost 11:00 - 14:00";
        String contact = "Kontakt... someone.";
        Canteen canteen = new Canteen(name, address, openingHours, contact);

        Course course = new Course();
        course.setName("Pasta");
        course.setDateOfServing(new Date());
        canteen.addCourse(course);

        Course course1 = new Course();
        course1.setName("Pasta something");
        course1.setDateOfServing(new Date());
        canteen.addCourse(course1);

        Canteen c = canteenRepository.save(canteen);
    }
}

ApplicationConfig.java

package dk.fitfit.campusfood.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(value = "dk.fitfit.campusfood.*")
public class ApplicationConfig {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);

    @Autowired
    DataInitializer dataInitializer;

    public ApplicationConfig() {
        logger.info("Application config loaded!");

//      DataInitializer dataInitializer = new DataInitializer();
        dataInitializer.initialize();
    }

    @Bean
    public DataInitializer dataInitializerBean() {
        return new DataInitializer();
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="dk.fitfit.campusfood.*" />

</beans:beans>
user672009
  • 4,379
  • 8
  • 44
  • 77
  • 1
    First, describe which class is a pojo. Second, describe what you mean by _autowiring fails_. – Sotirios Delimanolis Oct 18 '14 at 01:03
  • Don't create the object yourself. Spring can only autowire Spring-managed objects, ie. beans. – Sotirios Delimanolis Oct 18 '14 at 01:18
  • The object in question is canteenRepository. I'm not creating it. – user672009 Oct 18 '14 at 01:21
  • Your NPE is in `DataInitializer#initialize()` because `canteenRepository`, which is annotated with `@Autowired`, is `null`. It's `null` because Spring had absolutely nothing to do with it. It had absolutely nothing to do with it because you created the `DataInitializer` object yourself. – Sotirios Delimanolis Oct 18 '14 at 01:23
  • Sorry I'm confused. NPE? Should I autowire DataInitializer too? Am I going about this entirely wrong. I'm simply want to fill my database with some data. – user672009 Oct 18 '14 at 01:26
  • `NullPointerException`. [Here's how to handle them.](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it). Please read the duplicate about how to fix it. `DataInitializer` needs to be a bean (which you get from Spring's `ApplicationContext`) if anything is to be inject into it. – Sotirios Delimanolis Oct 18 '14 at 01:28
  • But I did try to annotate DataInitializer with both Service, Component and Configuration. And it's clearly null because spring (or rather me) fails to do the autowiring. – user672009 Oct 18 '14 at 01:36
  • You do this: `DataInitializer dataInitializer = new DataInitializer();`. Whether you've annotated the class or not, how do you expect Spring to do anything to the object you've created? If you have a `DataInitializer` **bean**, use that. It will have its `@Autowired` fields injected. – Sotirios Delimanolis Oct 18 '14 at 01:42
  • And if I uncomment dataInitializerBean, because I'm guessing I should, I get the same error... – user672009 Oct 18 '14 at 01:58
  • There are a lot of things you are missing here about the lifecycle of Java objects and the lifecycle of Spring beans. I recommend reading the duplicate and reading the Spring IoC documentation. (Constructors are ran before Spring can inject anything into fields.) – Sotirios Delimanolis Oct 18 '14 at 02:22
  • Thanks. I'm aware that I'm not up to code here. And your input is greatly appreciated. I'll read up! – user672009 Oct 18 '14 at 09:15

0 Answers0