Ошибка при создании bean-компонента с именем securityConfig: не удалось внедрить автоназначенные зависимости

1

Я пытаюсь объединить Java-config и xml-config для проверки подлинности под весной. Но я получил ошибку:

Ошибка при создании bean-компонента с именем "securityConfig": не удалось запустить автоматическое зависание

Какая проблема с моим кодом? Был поиск в Google для ответов, но не нашел.

Заранее спасибо. надеюсь, вы можете мне помочь.

Трассировки стека:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

java-config: SecurityConfig.java

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
     http
     .authorizeRequests()
         .antMatchers("/webapp/resources/**").permitAll() 
         .anyRequest().authenticated()
         .and()
     .formLogin()
         .loginPage("/login")
         .permitAll()
         .and()
     .logout()                                    
         .permitAll();
}

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

web.xml

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Я уже объявлял компонентное сканирование в моем servlet-context.xml

<context:component-scan base-package="ph.project.p3.conf" />
  • 0
    Как вы решили эту проблему?
Теги:
spring
spring-mvc
spring-java-config

2 ответа

2

Вы можете попробовать добавить аннотацию @Component. Таким образом, автоуслуги должны работать.

0

Вам нужно добавить <context:component-scan> в файл Spring-config. В противном случае ваше приложение не будет проверять структуру вашего пакета, чтобы находить и регистрировать компоненты в контексте приложения.

Синтаксис: <context:component-scan base-package="org.example.<yourapplicationName>"/> Например: <context:component-scan base-package="oph.project.p3.conf"/>

  • 0
    Привет @AnilSatija, спасибо за ответ. Как я уже говорил выше в своем вопросе, я уже объявил компонентное сканирование в моем servlet-context.xml и попробовал его также в моем root-context.xml. я также попытался "ph.project.p3" удалить .conf, но та же самая ошибка все еще произошла, не может autowire AuthorizationConfiguration.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню