@Autowired创建空对象,尽管@configuration

sha*_*haf 2 java spring dependency-injection

我有以下配置类

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在下面的@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试像这样调用process()时

FreeMarkerService f = new FreeMarkerService()
f.process() 
Run Code Online (Sandbox Code Playgroud)

我得到一个空异常,因为配置对象为空

我想使用@Autowired和@Configuration批注创建实例,我在做什么错呢?

lza*_*tos 5

您应该使用Spring实例化的FreeMarkerService对象,避免new对诸如Controllers或Services之类的对象使用关键字。

例如,

@Service
public class SampleService {

    @Autowired
    private FreeMarkerService freeMarkerService;

    public String callProcess() {
        return freeMarkerService.process();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在许多类似这样的帖子中找到更多详细信息。