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

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

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

В чем проблема с моим кодом? Гуглил ответы, но так и не нашел.

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

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

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-конфигурация: 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");
}
}

веб.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" />

person totoDaryl    schedule 24.04.2014    source источник
comment
Как вы решили эту проблему?   -  person Mr Roshan Pawar    schedule 31.03.2017


Ответы (2)


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

person Yannick Block    schedule 31.03.2015

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

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

person Anil Satija    schedule 24.04.2014
comment
Привет @AnilSatija, спасибо за ответ. Как я уже говорил выше в своем вопросе, я уже объявил компонентное сканирование в моем servlet-context.xml и попробовал его также в моем корневом контексте.xml. Я также пробовал ph.project.p3, удаляя .conf, но та же ошибка все равно возникала, не могу автоматически подключить AuthorizationConfiguration. - person totoDaryl; 24.04.2014