我正在编写自定义视图,并希望为Freemarker模板引擎注入一个配置如下,但 configurer 始终为空。
@Component
public class WkHtmlToPdfView extends AbstractView {
private Logger logger = Logger.getLogger(this.getClass().toString());
@Inject
private FreeMarkerConfigurer configured;
Bean配置正确,因为在Controller中它被正确注入:
@Controller
@RequestMapping("/dashboard")
public class DashboardController {
@Inject
private FreeMarkerConfigurer configured;
配置并不像我想的那么特别:
@Configuration
@EnableWebMvc
@EnableJpaRepositories(basePackages = {"com.xxxxxx.yy.repository" })
@EnableTransactionManagement
@ComponentScan(basePackages = "com.xxxxxx.yy")
@PropertySource("classpath:application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
factory.setTemplateLoaderPath("classpath:WEB-INF/templates");
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
freemarker.template.Configuration config = factory.createConfiguration();
config.setIncompatibleImprovements(new Version(2, 3, 20));
config.setDefaultEncoding("UTF-8");
config.setLocale(Locale.GERMANY);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setObjectWrapper(new BeansWrapper());
result.setConfiguration(config);
return result;
}
是否无法将Bean注入视图?我错过了什么? 谢谢你的帮助!
编辑1
我的视图位于子包视图中。我有一个AppConfig,我错过了提及。 实际上它看起来像这样。
@Configuration
@ComponentScan(basePackages = { "com.xxxxxx.yy" }, excludeFilters = { @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION) })
public class AppConfig {
}
但如果我设置
@ComponentScan(basePackages = { "com.xxxxxx.yy", "com.xxxxxx.yy.view" }
它有效! 你能解释一下有什么区别吗?我以为子包也会被扫描。在WebAppConfig中扩展ComponentScan没有效果 - 为什么?