java 创建名为“defaultServletHandlerMapping”的 bean 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34522622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:59:44  来源:igfitidea点击:

Error creating bean with name 'defaultServletHandlerMapping

javamavenspring-mvcservletsspring-security

提问by Edwardo S

This is a spring (with spring security) + java + maven application on eclipse. I encounter the following error when Submit a signup form. See the rest of my files subsequently:

这是eclipse上的spring(带spring security)+java+maven应用。提交注册表单时遇到以下错误。随后查看我的其余文件:

HTTP Status 500 - Request processing failed; nested exception is 
org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'defaultServletHandlerMapping' defined in class 
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: 
Bean instantiation via factory method failed; nested exception is 
org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[org.springframework.web.servlet.HandlerMapping]:
 Factory method 'defaultServletHandlerMapping'
 threw exception; nested exception is java.lang.IllegalArgumentException:
 A ServletContext is required to configure default servlet handling

My files:

我的文件:

AppInit

应用初始化

package com.myapp.config;

import org.springframework.security.web.context.*;

public class AppInit       extends AbstractSecurityWebApplicationInitializer                    

}

MyApp config file:

MyApp 配置文件:

package com.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.myapp.JDBC.EmailJDBC;
import com.myapp.JDBC.LastIdJDBC;
import com.myapp.JDBC.LoginJDBC;
import com.myapp.JDBC.PersonJDBC;

@EnableWebMvc //mvc:annotation-driven
@Configuration

@ComponentScan(basePackages ={ "com.myapp" })//, excludeFilters = { 
//@Filter(type = FilterType.ANNOTATION, value = Configuration.class) })

public class myappConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

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

    @Bean
    public DriverManagerDataSource getDatasource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setPassword("1234567");
        dataSource.setUrl("jdbc:mysql://localhost:3306/myapp");
        dataSource.setUsername("root");
        return dataSource;
    }
    @Bean
    public LoginJDBC getLoginBean(){
        LoginJDBC bean = new LoginJDBC();
        bean.setDataSource(new myappConfig().getDatasource());
        return bean;
    }
    @Bean
    public PersonJDBC getPersonBean(){
        PersonJDBC bean = new PersonJDBC();
        bean.setDataSource(new myappConfig().getDatasource());
        return bean;
    }
    @Bean
    public EmailJDBC getEmailBean(){
        EmailJDBC bean = new EmailJDBC();
        bean.setDataSource(new myappConfig().getDatasource());
        return bean;
    }
    @Bean
    public LastIdJDBC getLastIdBean(){
        LastIdJDBC bean = new LastIdJDBC();
        bean.setDataSource(new myappConfig().getDatasource());
        return bean;
    }
}

WebInit file:

网络初始化文件:

package com.myapp.config;

import javax.servlet.Filter;

import org.springframework.core.annotation.Order;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;


public class myappWebInit extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { myappConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/","/login", "/signuPerson","/regPerson","/regPersonSuccess" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { RootConfiguration.class };
    }
    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] { new HiddenHttpMethodFilter() };
    }
}

Security config file:

安全配置文件:

package com.myapp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private CsrfTokenRepository csrfTokenRepository() 
    { 
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
        repository.setSessionAttributeName("_csrf");
        return repository; 
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

    http
        .csrf()
            .csrfTokenRepository(csrfTokenRepository())
            .and()
        .authorizeRequests()
            .antMatchers("/resources/**", "/signuPerson").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            //.failureUrl(authenticationFailureUrl)
            .permitAll()
            .and()
        .logout()
            .permitAll();


    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

I apologize for putting a lot of stuff. I already tried a solution to a problem similar to this but it didn't workout. Any hint would be much appreciated. Thanks in advance!

我很抱歉放了很多东西。我已经尝试过类似此问题的解决方案,但它没有锻炼。任何提示将不胜感激。提前致谢!

回答by Edwardo S

I solved the problem with help from a solution to a similar problem on this Platform.

我在此平台上类似问题的解决方案的帮助下解决了该问题。

I excluded configuration filters from being scanned by putting the following annotations in the myappconfig file:

我通过在 myappconfig 文件中添加以下注释来排除配置过滤器的扫描:

@EnableWebMvc 
@Configuration
@ComponentScan(
  basePackages ={ "com.myapp" }, 
  excludeFilters = { 
    @Filter(type = FilterType.ANNOTATION, value = Configuration.class)
  }
)

After doing this, the problem was not solved.

这样做之后,问题并没有解决。

Then I removed @EnableWebMvcand put in myappinit file and issue was solved.

然后我删除@EnableWebMvc并放入 myappinit 文件,问题解决了。

My guess is that @EnableWebMvcand @ComponentScan(basePackages ={ "com.myapp" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })shouldn't be in the same config file.

我的猜测是,@EnableWebMvc@ComponentScan(basePackages ={ "com.myapp" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })不应该在同一个配置文件。