5
votes

I asked a similar question and thought it was answered. However, yesterday it stopped working so I am going to ask again, but with my modified classes. I hope that is the right protocol for this....

I have a spring-boot-starter-web that is throwing a null pointer on startup because one of the classes isn't being Autowired. Here is my setup:

package com.company.product
@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration
public class OFAC {
    public static void main(String[] args) {
        ApplicationContext ofac = SpringApplication.run( OFAC.class, args );
    }
}

In a subpackage I have: package com.company.product.configuration @Configuration @ComponentScan() public class OFAConfiguration {

    @Autowired
    private ConfigurationSettings configurationSettings;

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        int port = 9000;
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();

        if ( configurationSettings.getServerPort()!= null ) {
            port = Integer.parseInt( configurationSettings.getServerPort());
        }
        factory.setPort( port );
        factory.setSessionTimeout( 30, TimeUnit.MINUTES );
        factory.addErrorPages( new ErrorPage( HttpStatus.NOT_FOUND, "/notfound.html" ) );


        return factory;
    }
..}

This following class is null when @Autowired, but I can set a breakpoint and see it initialized. package com.company.product.configuration @Component @ConfigurationProperties() public class ConfigurationSettings {

    @Value("${ofac.appName}")
    private String appName;
    @Value("${ofac.appDescription}")
    private String appDescription;
    @Value("${ofac.serverPort}")
    private String serverPort;
// getters and setters
..
}

This is where a null pointer is thrown because ConfigurationSettings is null: package com.company.product.service @Component public class FileDownloadService {

    @Autowired
    private ConfigurationSettings configurationSettings;

    private List<String> paths = new ArrayList<String>();

    public FileDownloadService() {
        paths.add( configurationSettings.getFileDownloadSdn() );
        paths.add( configurationSettings.getFileDownloadAdd() );
        paths.add( configurationSettings.getFilDownloadAlt() );
        paths.add( configurationSettings.getFileDownloadXmlHeader() );
    }

Here is my log output:

:: Spring Boot ::            (v1.0.0.RC4)

2014-03-14 17:59:16.975  INFO 41410 --- [           main] com.company.product.OFAC                : Starting OFAC on Edelweiss.local with PID 41410 (/Users/David/projects/cnet/OFAC/out/production/OFAC started by...)
2014-03-14 17:59:16.981 DEBUG 41410 --- [           main] o.s.boot.SpringApplication               : Loading source class com.company.product.OFAC
2014-03-14 17:59:17.517  INFO 41410 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@64de5c64: startup date [Fri Mar 14 17:59:17 MDT 2014]; root of context hierarchy
2014-03-14 17:59:17.522 DEBUG 41410 --- [           main] ationConfigEmbeddedWebApplicationContext : Bean factory for org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@64de5c64: org.springframework.beans.factory.support.DefaultListableBeanFactory@600f2cb8: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,OFAC]; root of factory hierarchy
2014-03-14 17:59:20.249 DEBUG 41410 --- [           main] ationConfigEmbeddedWebApplicationContext : Using MessageSource [org.springframework.context.support.ReloadableResourceBundleMessageSource: basenames=[classpath:messages/messages,classpath:messages/validation]]
2014-03-14 17:59:20.249 DEBUG 41410 --- [           main] ationConfigEmbeddedWebApplicationContext : Using ApplicationEventMulticaster [org.springframework.context.event.SimpleApplicationEventMulticaster@4e5197fd]
2014-03-14 17:59:25.590 DEBUG 41410 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: /..gvm/gradle/1.10/bin/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/1.0.0.RC4/b8934d1dcdfd6f454ad86ea7372fd8a6dd2f6e61/spring-boot-1.0.0.RC4.jar
2014-03-14 17:59:25.591 DEBUG 41410 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: /..gvm/gradle/1.10/bin/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/1.0.0.RC4/b8934d1dcdfd6f454ad86ea7372fd8a6dd2f6e61/spring-boot-1.0.0.RC4.jar
2014-03-14 17:59:25.591 DEBUG 41410 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Document root: /Users/me/projects/cnet/OFAC/src/main/webapp
2014-03-14 17:59:25.642  INFO 41410 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 9001
2014-03-14 17:59:26.156  INFO 41410 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-03-14 17:59:26.157  INFO 41410 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-14 17:59:26.463  INFO 41410 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-14 17:59:26.464  INFO 41410 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 8954 ms
2014-03-14 17:59:27.348  INFO 41410 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-14 17:59:27.353  INFO 41410 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-03-14 17:59:28.064  INFO 41410 --- [ost-startStop-1] o.a.catalina.util.SessionIdGenerator     : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
2014-03-14 17:59:28.232  INFO 41410 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Creating embedded database 'ofac'
2014-03-14 17:59:28.509  INFO 41410 --- [           main] o.s.j.d.init.ResourceDatabasePopulator   : Executing SQL script from class path resource [h2.sql]
2014-03-14 17:59:28.526  INFO 41410 --- [           main] o.s.j.d.init.ResourceDatabasePopulator   : Done executing SQL script from class path resource [h2.sql] in 17 ms.
2014-03-14 17:59:28.763  INFO 41410 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2014-03-14 17:59:28.814  INFO 41410 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2014-03-14 17:59:29.117  INFO 41410 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.1.Final}
2014-03-14 17:59:29.120  INFO 41410 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2014-03-14 17:59:29.123  INFO 41410 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2014-03-14 17:59:29.545  INFO 41410 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
2014-03-14 17:59:29.684  INFO 41410 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2014-03-14 17:59:29.846  INFO 41410 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2014-03-14 17:59:30.010  INFO 41410 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
2014-03-14 17:59:30.011  INFO 41410 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000102: Fetching database metadata
2014-03-14 17:59:30.014  INFO 41410 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000396: Updating schema
2014-03-14 17:59:30.015  INFO 41410 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000232: Schema update complete
2014-03-14 17:59:39.493  INFO 41410 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2014-03-14 17:59:39.558  INFO 41410 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

   AopAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.context.annotation.EnableAspectJAutoProxy,org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration: ${spring.aop.auto:true} (OnExpressionCondition)

   AopAutoConfiguration.JdkDynamicAutoProxyConfiguration
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration: !${spring.aop.proxyTargetClass:false} (OnExpressionCondition)

   JpaRepositoriesAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found the following [dataSource] @ConditionalOnMissingBean (types: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; SearchStrategy: all) found no beans (OnBeanCondition)

   JpaRepositoriesAutoConfiguration.JpaWebConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnMissingBean (types: org.springframework.data.web.PageableHandlerMethodArgumentResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration
      - existing auto database detected (DataSourceAutoConfiguration.DatabaseCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#jdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#namedParameterJdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceTransactionManagerAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

   JmxAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration: ${spring.jmx.enabled:true} (OnExpressionCondition)
      - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: all) found no beans (OnBeanCondition)

   HibernateJpaAutoConfiguration
      - found HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager (OnClassCondition)

   JpaBaseConfiguration.JpaWebConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration: ${spring.jpa.openInView:${spring.jpa.open_in_view:true}} (OnExpressionCondition)
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor,org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; SearchStrategy: all) found no beans (OnBeanCondition)

   ThymeleafAutoConfiguration
      - @ConditionalOnClass classes found: org.thymeleaf.spring4.SpringTemplateEngine (OnClassCondition)

   ThymeleafAutoConfiguration.DefaultTemplateResolverConfiguration
      - @ConditionalOnMissingBean (names: defaultTemplateResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   ThymeleafAutoConfiguration.ThymeleafDefaultConfiguration
      - @ConditionalOnMissingBean (types: org.thymeleaf.spring4.SpringTemplateEngine; SearchStrategy: all) found no beans (OnBeanCondition)

   ThymeleafAutoConfiguration.ThymeleafViewResolverConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet (OnClassCondition)
com.edelweissco.ofac
   ThymeleafAutoConfiguration.ThymeleafViewResolverConfiguration#thymeleafViewResolver
      - @ConditionalOnMissingBean (names: thymeleafViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   DispatcherServletAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration
      - no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
      - @ConditionalOnClass classes found: javax.servlet.ServletRegistration (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   HttpMessageConvertersAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)

   HttpMessageConvertersAutoConfiguration#messageConverters
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers
      - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers#jacksonObjectMapper
      - @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration.ObjectMappers#mappingJackson2HttpMessageConverter
      - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)

   ServerPropertiesAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   ServerPropertiesAutoConfiguration#serverProperties
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.ServerProperties; SearchStrategy: current) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration#hiddenHttpMethodFilter
      - @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#requestContextListener
      - @ConditionalOnMissingBean (types: org.springframework.web.context.request.RequestContextListener; SearchStrategy: all) found no beans (OnBeanCondition)


Negative matches:
-----------------

   MessageSourceAutoConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found the following [messageSource] (OnBeanCondition)

   RabbitAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

   AopAutoConfiguration.CglibAutoProxyConfiguration
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$CglibAutoProxyConfiguration: ${spring.aop.proxyTargetClass:false} (OnExpressionCondition)

   BatchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)

   MongoRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

   MongoTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.core.MongoTemplate (OnClassCondition)

   DataSourceAutoConfiguration.DbcpConfiguration
      - Tomcat DataSource (DataSourceAutoConfiguration.BasicDatabaseCondition)

   DataSourceAutoConfiguration.EmbeddedConfiguration
      - existing non-embedded database detected (DataSourceAutoConfiguration.EmbeddedDatabaseCondition)

   DataSourceAutoConfiguration.TomcatConfiguration
      - found database driver org.h2.Driver (DataSourceAutoConfiguration.TomcatDatabaseCondition)
      - @ConditionalOnMissingBean (types: javax.sql.DataSource; SearchStrategy: all) found the following [dataSource] (OnBeanCondition)

   DataSourceTransactionManagerAutoConfiguration#transactionManager
      - @ConditionalOnMissingBean (names: transactionManager; SearchStrategy: all) found the following [transactionManager] (OnBeanCondition)

   DataSourceTransactionManagerAutoConfiguration.TransactionManagementConfiguration
      - required @ConditionalOnMissing classes found: org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration (OnClassCondition)

   JmsTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)

   DeviceResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

   MongoAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo (OnClassCondition)

   JpaBaseConfiguration#entityManagerFactory
      - @ConditionalOnMissingBean (names: entityManagerFactory; SearchStrategy: all) found the following [entityManagerFactory] (OnBeanCondition)

   JpaBaseConfiguration#jpaVendorAdapter
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.JpaVendorAdapter; SearchStrategy: all) found the following [jpaVendorAdapter] (OnBeanCondition)

   JpaBaseConfiguration#transactionManager
      - @ConditionalOnMissingBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found the following [transactionManager] (OnBeanCondition)

   ReactorAutoConfiguration
      - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)

   RedisAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.redis.connection.lettuce.LettuceConnection,org.springframework.data.redis.core.RedisOperations,com.lambdaworks.redis.RedisClient (OnClassCondition)

   SecurityAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.security.authentication.AuthenticationManager (OnClassCondition)

   ThymeleafAutoConfiguration.ThymeleafSecurityDialectConfiguration
      - required @ConditionalOnClass classes not found: org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect (OnClassCondition)

   ThymeleafAutoConfiguration.ThymeleafWebLayoutConfiguration
      - required @ConditionalOnClass classes not found: nz.net.ultraq.thymeleaf.LayoutDialect (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedJetty
      - required @ConditionalOnClass classes not found: org.eclipse.jetty.server.Server,org.eclipse.jetty.util.Loader (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found the following [servletContainer] (OnBeanCondition)

   MultipartAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
      - @ConditionalOnBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebSocketAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)

Here is the stack trace, just a standard NullPointerException. The ConfigurationSetting has been instantiated (according to debugger) prior to this call. But when the FileDownloadService is created, the ConfigurationSetting is null.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileDownloadService' defined in file [.cnet/OFAC/out/production/OFAC/com/company/product/service/FileDownloadService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.company.product.service.FileDownloadService]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076) 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:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1014) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:957) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ... 18 more Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.company.product.service.FileDownloadService]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069) ... 29 more Caused by: java.lang.NullPointerException at com.company.product.service.FileDownloadService.(FileDownloadService.java:29) 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) ... 31 more

Now I swear after some very good StackOverflow help last week this was all working. However, I cannot run my app now because the null pointer on startup.

1
You probably need to give us more (like a whole project). If you can see the ConfigurationSettings being initialized, can you can grab the stack trace from there? Ditto the FileDownloadService. I assume the latter is being forced to initialize too early. I'm also very suspicious of the EmbeddedServletContainerFactory inside your ConfigurationSettings (@ConfigurationProperties work best if they are just Java beans). But hard to be sure without more context.Dave Syer
I have updated my post with the modified classes (I moved the EmbeddedTomcat to the OFACConfiguration per your suggestion) and log statements. If I set a breakpoint, I can step thru bootup and see everything being initialized until it gets to the FileDownloadService, where configurationSettings is null and throws the NPE.sonoerin
I don't see the stack trace? Also you are doing something a abut weird with the ConfigurationSettings, since you have both @ConfigurationProperties and @Value annotations wiring it up (that wouldn't cause an autowiring problem, but it's odd).Dave Syer
I added the stack trace. I also added the package to the code sample above, but basically I have my OFAC application at root, the configuration classes in /configuration, and everything else in their own child package. I have the @Value in my ConfigurationSettings or the attributes never get set with the application.properties values.sonoerin
The @Value is redundant. If those fields aren't being bound you have other issues.Dave Syer

1 Answers

3
votes

Sorry, should have seen this earlier but the stack trace makes it obvious: it's not a spring autowiring error because spring never gets to see an instance of your FileDownloadService - you are using an uninitialized field in its constructor. If you want to refer to an @Autowired field in an initializer, use @PostConstruct not the constructor.