Использую в одном проекте и xml и annotations конфигурации.
Когда пытаюсь сделать @Autowired
в классе конфигурации spring-security, выбивает ошибку
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.khodan.caferacer.service.UserService com.khodan.caferacer.service.UserDetailsServiceImpl.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.khodan.caferacer.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
И:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.khodan.caferacer.service.UserService com.khodan.caferacer.service.UserDetailsServiceImpl.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.khodan.caferacer.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.khodan.caferacer.service.UserService com.khodan.caferacer.service.UserDetailsServiceImpl.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.khodan.caferacer.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 55 more
Сам интерфейс UserService:
public interface UserService extends JpaRepository<User, Long> {
public User findByEmail(String email);
}
Класс UserDetailServiceImpl, который и выкидывает данную ошибку:
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Autowired
public UserDetailsServiceImpl(UserService userService){
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String name)
throws UsernameNotFoundException {
User user = userService.findByEmail(name);
if(user==null){
throw new UsernameNotFoundException("User: "+name+" not found");
}
ModelUserDetails principal = ModelUserDetails.getBuilder()
.firstName(user.getFirstName())
.id(user.getId())
.lastName(user.getLastName())
.password(user.getPassword())
.role(user.getRole())
.socialSignInProvider(user.getSignInProvider())
.username(user.getEmail())
.build();
return principal;
}
}
root-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based
configuration) -->
<context:annotation-config />
<!-- Определяем папки, в которых будем автоматически искать бины-компоненты
(@Component, @Service) -->
<context:component-scan base-package="com.khodan.caferacer" />
<!-- Sets the Entity Manager Factory, Data source and the JPA implementation
framework -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.khodan.caferacer.model" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5433/caferacer" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
<!-- Provides auto-injecting EntityManager into the DAOs field with annotation
@PersistenceContext -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Provides translation native under layer Exceptions into Spring Exceptions
in DAOs classes with annotation @Repository -->
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- Provides declarative transaction management -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<context:component-scan base-package="com.project.traceplace">
<!-- Avoids to duplicate class scan in root-context and application-servlet.xml -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
В этом файле так же выбивает ошибку автовайрета:
@SuppressWarnings("deprecation")
@Configuration
@EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authenticate")
.failureUrl("/login?error=bad_credentials")
.and()
.logout()
.deleteCookies("JSESSIONID")
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.and()
.authorizeRequests()
.antMatchers(
"/auth/**",
"/login",
"/signup/**",
"/user/register/**"
).permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.apply(new SpringSocialConfigurer());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return (PasswordEncoder) new BCryptPasswordEncoder(10);
}
@Bean
public SocialUserDetailsService socialUserDetailsService() {
return new SocialUserDetailsServiceImpl(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl(userService);
}
}
UserService
либо должна быть аннотация@Repository
, либо в XML включен тэгjpa:repositories
.@Autowired
ставить не нужно. Лучше уберите конструктор совсем, и делайте инжект через сеттер.@Repository
но не помогло@Autowired private UserService userService;
удалить полностью?Error creating bean with name 'securityContext': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.khodan.caferacer.service.UserService com.khodan.caferacer.config.SecurityContext.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.khodan.caferacer.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.