2

I have the following configuration class

@org.springframework.context.annotation.Configuration
public class TemplateConfiguration {

    @Bean
    public Configuration configuration() {
        Configuration configuration = new Configuration(new Version(2, 3, 23));
        configuration.setClassForTemplateLoading(TemplateConfiguration.class, "/templates/");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setLocale(Locale.US);
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        return configuration;
    }
}

and I use it at the following @service

@Service
public class FreeMarkerService {

    @Autowired
    private Configuration configuration;

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

    public String process() {
        try {
            Template template = configuration.getTemplate("someName");
            ....
        } catch (IOException | TemplateException e) {
            logger.error("Error while processing FreeMarker template: " + e);
            throw new RuntimeException(e);
        }
    }
}

but when I try to call process() like

FreeMarkerService f = new FreeMarkerService()
f.process() 

I get a null exception cause the configuration Object is null

I want to create an instance using @Autowired and @Configuration annotations what am I doing wrong?

shahaf
  • 4,750
  • 2
  • 29
  • 32

4 Answers4

5

You should use the Spring instantiated FreeMarkerService object avoiding use of new keyword for objects like Controllers or Services as possible.

For example,

@Service
public class SampleService {

    @Autowired
    private FreeMarkerService freeMarkerService;

    public String callProcess() {
        return freeMarkerService.process();
    }
}

More details you can find in many posts like this.

lzagkaretos
  • 2,842
  • 2
  • 16
  • 26
2

This is a member injection:

@Autowired
private static Configuration configuration;

Which spring does after instantiating the bean from its constructor. So at the time you are making that static method call spring has not injected the value.

  • so, what should I do? cause even after removing the static modifier , spring doesn't create the Configuration class , and configuration is still null – shahaf Sep 11 '17 at 12:54
1

This is because you are trying to autowire a static field. This is not possible in Spring. Remove static from your Configuration property and it should work.

@Autowired
private Configuration configuration;
Plog
  • 9,164
  • 5
  • 41
  • 66
1
 @Autowired
 private static Configuration configuration;

Why autowired a static field? this is the reason. static member load as class definition load so it is not getting injected value and getting default value which is null.