Spring 5 - 无 ServletContext 设置异常

2024-01-07

当我尝试使用 Spring 5 运行我的应用程序时AnnotationConfigApplicationContext类,获取异常No ServletContext set.

这是我的主要方法:

public class Run {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.register(AppConfig.class);
        context.register(WebConfig.class);
        context.register(WebAppInitializer.class);
        context.refresh();

        MainService mainService = (MainService ) context.getBean("mainService ");
        mainService.loadData();
    }

}

AppConfig定义 transactionManager 和 sessionFactory bean:

@PropertySource("classpath:hibernate.properties")
@EnableTransactionManagement
@Configuration
@ComponentScan(basePackages = {"com.tk"})
@ComponentScans(value = { @ComponentScan("com.tk.spring4App.service"),
                          @ComponentScan("com.tk.spring4App.dao") })
public class AppConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

        Properties props = new Properties();
        // Setting JDBC and hibernate properties

        factoryBean.setHibernateProperties(props);
        factoryBean.setAnnotatedClasses(SampleObject.class);
        return factoryBean;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }

}

这是我的WebConfig class:

@PropertySource({
        "classpath:mail.properties",
        "classpath:ldap.properties"
})
@EnableScheduling
@EnableAspectJAutoProxy
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"com.tk"})
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private Environment env;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/")
                .setCachePeriod(3600)
                .resourceChain(true)
                .addResolver(new PathResourceResolver());
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getMultipartResolver() {
        return new CommonsMultipartResolver();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("classpath:messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ControllerInterceptor()).addPathPatterns("/*");
    }

    @Bean
    public TaskScheduler taskExecutor() {
        return new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(3));
    }

    @Bean(name = "mailSender")
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        mailSender.setHost(env.getRequiredProperty("mail.host"));
        mailSender.setPort(Integer.parseInt(env.getRequiredProperty("mail.port")));
        mailSender.setUsername(env.getRequiredProperty("mail.username"));
        mailSender.setPassword(env.getRequiredProperty("mail.password"));

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", env.getRequiredProperty("mail.transport.protocol"));
        props.put("mail.smtp.auth", env.getRequiredProperty("mail.smtp.auth"));
        props.put("mail.smtp.starttls.enable", env.getRequiredProperty("mail.smtp.starttls.enable"));
        props.put("mail.debug", env.getRequiredProperty("mail.debug"));

        return mailSender;
    }

    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap.url"));
        contextSource.setBase(env.getRequiredProperty("ldap.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap.password"));
        return contextSource;
    }

    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }

}

The WebAppInitializer类只需初始化应用程序:

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        servletContext.addFilter("characterEncodingFilter", characterEncodingFilter).addMappingForUrlPatterns(null, false, "/*");
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.tk.spring4App.config");
        return context;
    }

}

我设法找到了发生这种情况的原因。 我的配置被分成几个文件,并且我在安全配置(之前创建的)中创建了一个与 MVC 相关的 bean,强制提前使用 MVC 配置。

解决方案是将 @Bean 实例从安全配置移动到 MVC 配置。 我希望它能帮助其他人!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 5 - 无 ServletContext 设置异常 的相关文章

随机推荐

  • ClientBase 未实现 IDisposable 成员

    如果 Dispose 方法声明不可见 声明 那么 System ServiceModel ClientBase 抽象类如何实现 IDisposable 接口 如果我尝试做同样的事情 我会收到错误并且无法编译 abstract class A
  • SQL Server - 按小时、多天查询

    我希望使用 datepart 运行 SQL 查询 将数据拆分为每小时增量 然后使该查询运行多天 目前 我只是将日期增加一天 然后运行多个查询 我想知道是否有一种方法可以将这一切合并到一个查询中 该查询将提供整个日期范围的输出 select
  • php 中特定日期的上一个工作日

    我正在寻找获取特定日期的最后一个工作日的最佳方法 我使用的示例是平安夜 12 月 24 日 前的最后一个工作日 不幸的是这不起作用 echo date l jS of F Y h i s A strtotime last weekday b
  • .Net 4.5:我应该使用 IDataErrorInfo 还是 INotifyDataErrorInfo?

    我以前用过IDataErrorInfo在我的 MVVM WPF 应用程序中 现在之后INotifyDataErrorInfo在 Net 4 5中可用 是否最好替换IDataErrorInfo或继续使用旧方法IDataErrorInfo 有许
  • 对象函数 (a,b){return new e.fn.init(a,b,h)} 没有方法 'cookie'

    试图获取 a 的值cookie如果它设置并更新div与cookievalue 否则生成一个80 100之间的随机数 将其设置为cookie 然后更新div 我收到错误 Object function a b return new e fn
  • 如何在 html 元素上重写 onkeydown ?

    我继承了一个在弹出窗口中实现禁用 F5 的应用程序 但是 如果用户单击窗口正文下方并按 F5 页面仍会刷新 我将函数调用移至 现在 F5 被禁用 一切都按预期工作 然而 这不是放置代码的最佳位置 如果我可以在我的代码中执行如下所示的操作 我
  • 是什么让 React 库需要 preact-compat?

    我注意到某些图书馆 例如classnames在 Preact 中很容易获得 但其他人喜欢styled components要求preact compat 是什么使得 React 库在 preact 中不受本机支持而需要使用 preact c
  • 函数中返回向量后清除内存

    我有一个函数 可以在其中处理和存储大量数据 然后将结果作为类向量返回 该函数中存储的数据量巨大 我想在该函数完成工作后清除该函数的存储内存 是否有必要这样做 该函数是否自动清除内存 或者我应该通过某些函数清除内存 Update vector
  • 需要将 git 分支重置为原始版本

    我不小心在一个本来不应该在的分支上工作了一段时间 所以我从它的分支上给它起了适当的名字 现在我想将我不应该进入的分支覆盖到原始版本 github 是否有捷径可寻 我尝试删除分支 然后重置跟踪分支 但它只是给了我再次正在处理的版本 如果你还没
  • 根据给定索引和元素数量的列表创建子列表。序言

    我正在尝试解决一个简单的序言问题 但我无法解决它 从列表中 需要创建一个给定索引 I 的子列表 然后从 I 中创建一个给定为 N 的下一个元素 如果索引大于列表长度 我将使子列表为空 如果 N 元素数量 大于列表中的其余元素 我将获得从 I
  • StackExchange API - 反序列化 JSON 响应中的日期

    我正在尝试使用 stackexchange api 我正在尝试获取一些用户信息 如果运行 您将获得 JSON 响应 items badge counts bronze 5630 silver 4212 gold 267 account id
  • 在Python中交换链表中的对,一个链接消失了?

    我一直在学习链表 并且在 python 中实现链表比我预期的要容易 然而 当涉及到解决 交换链表中的对 的问题时 由于某种原因 我的第二个链接在交换过程中消失了 我已经盯着这个问题很多年了 并尝试了在网上找到的不同解决方案 他们都得到相同的
  • 如何在 Swift 中使用闭包从字符串中提取两个整数来执行计算

    我目前正在使用mapSwift 中带有闭包的属性 用于从数组中提取线性因子并计算跨越一个八度音阶的音乐频率列表 let tonic Double 261 626 middle C let factors 1 0 1 125 1 25 1 3
  • 从 icc 获取 Intel 语法 asm 输出,而不是默认的 AT&T 语法?

    我陷入了一个问题 我已经使用 gcc 编译 汇编我的 C 代码一段时间了 并习惯于阅读 Intel 汇编语法 我用的是 masm intel生成程序集文件时的标志 但最近因为公司迁移 他们得到了Intel的icc 声称更好 所以现在我需要使
  • 访问 try-catch 块外部的变量

    我有以下代码 class ClassA public ClassA std string str std string GetSomething int main std string s try ClassA a ClassA s cat
  • 仅使用 css 而不使用 javascript 在悬停时显示叠加层

    当我将鼠标悬停在导航栏菜单上时 我试图制作整页叠加ul 覆盖层div位于页面顶部 当我将鼠标悬停在ul the li链接出现 但覆盖层不出现 我怎样才能使用 CSS 来显示叠加层 有人可以帮忙吗 这是 HTML 和 CSS 代码 标题的完整
  • 如何在 REST Web 服务中发送 JSON 数据?

    如何在 REST Web 服务中发送 JSON 数据 我有一个 json 对象 其中包含产品 Id 商店 Id 价格 产品单位 数量 值 这里除产品单位值外 所有值均为整数 现在 我想将这些值发送到其余的 Web 服务中 能否请您提供一些样
  • Angular2 Safari 后退按钮

    在实际的 Angular2 beta 14 及之前的版本 中 Safari 实际上使用 9 1 上的后退按钮 使用路由和多个视图时 似乎存在问题 https github com angular angular issues 7722 ht
  • 协议对保留计数有影响吗?

    我有一个非常简单的代码 我是故意使用委托创建内存循环 尝试观察和学习如何使用 Xcode 的 Memory Graph 我不明白的是为什么在连接部分 Xcode 说有3连接 应该只有2个 如果我用闭包创建一个内存循环 那么它会显示2连接 我
  • Spring 5 - 无 ServletContext 设置异常

    当我尝试使用 Spring 5 运行我的应用程序时AnnotationConfigApplicationContext类 获取异常No ServletContext set 这是我的主要方法 public class Run public