1

После запуска проекта на jetty/tomcat выкидывает такой exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityContext': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.dronesfree.configuration.SecurityContext.userDetailsService; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'userDetailsService': Requested bean is currently in creation: Is there an unresolvable circular reference?

Самое забавное, что проект вчера запускался. После того как я переустановил себе ОС с win7 на ubuntu 14.04 проект перестал запускаться. БД установлена, подключение создано, все для разработки есть. Вот мой бин, который не может быть создан

SecurityContext:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.social.security.SpringSocialConfigurer;

import com.dronesfree.security.service.RepositoryUserDetailsService;
import com.dronesfree.security.service.SimpleSocialUserDetailsService;
import com.dronesfree.user.service.UserService;

@Configuration
@EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private UserService userService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

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

        http
        // Configures form login
        .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login/authenticate")
                .failureUrl("/login?error=bad_credentials")
                .usernameParameter("username")
                .passwordParameter("password")
                // Configures the logout function
                .and()
                .logout()
                .deleteCookies("JSESSIONID")
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                // Configures url based authorization
                .and()
                .authorizeRequests()
                // Anyone can access the urls
                .antMatchers("/", "/auth/**", "/login", "/signup/**",
                        "/user/register/**")
                .permitAll()
                // The rest of the our application is protected.
                .antMatchers("/**")
                .access("hasRole('ROLE_USER')")
                // Adds the SocialAuthenticationFilter to Spring Security's
                // filter chain.
                .and().csrf().and().exceptionHandling()
                .accessDeniedPage("/403").and()
                .apply(new SpringSocialConfigurer());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
        // Spring Security ignores request to static resources such as CSS or JS
        // files.
        .ignoring().antMatchers("/static/**");
    }

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SocialUserDetailsService socialUserDetailsService() {
        return new SimpleSocialUserDetailsService(userDetailsService());
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new RepositoryUserDetailsService(userService);
    }
}’

RepositoryUserDetailsService:

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dronesfree.security.dto.ExampleUserDetails;
import com.dronesfree.user.model.User;
import com.dronesfree.user.service.UserService;

@Service("userDetailsService")
public class RepositoryUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    private static final Logger LOGGER = Logger
            .getLogger(RepositoryUserDetailsService.class);

    public RepositoryUserDetailsService(UserService userService) {
        this.userService = userService;
    }

    @Transactional(readOnly = true)
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        LOGGER.debug("Loading user by username: {" + username + "}");

        User user = userService.getUserByUsername(username);
        LOGGER.debug("Found user: {" + user + "}");

        if (user == null) {
            throw new UsernameNotFoundException("No user found with username: "
                    + username);
        }

        ExampleUserDetails principal = ExampleUserDetails.getBuilder()
                .firstName(user.getFirstName()).id(user.getId())
                .lastName(user.getLastName()).password(user.getPassword())
                .role(user.getRole())
                .socialSignInProvider(user.getSignInProvider())
                .username(user.getUsername()).build();

        LOGGER.debug("Returning user details: {" + principal + "}");

        return principal;

    }

}
2
  • А зачем вам конструктор с параметром в бине? По идеи бины должны быть с дефолтным конструктором.
    – Vartlok
    1 окт 2015 в 11:48
  • Если вам дан исчерпывающий ответ, отметьте его как верный (галка напротив выбранного ответа). 2 окт 2015 в 14:16

1 ответ 1

1

У Spring (насколько понял, доки подробно не читал) есть следующий workflow:

  • Spring находит необходимые пакеты, указанные в @ComponentScan, сканирует их на предмет классов, отмеченных @Configuration, @Service, @Component, @Repository и аналогичными аннотациями и загружает в контейнер
  • Контейнер строит граф зависимостей всего это добра
  • Spring запрашивает у контейнера все объявленные бины
  • Контейнер разрешает дерево зависимостей для выбранного бина, используя @Autowired для определения этих зависимостей
  • В случае наличия @Autowired-полей класс сначала создается, а затем они проставляются через рефлексию

Очевидно, на последнем этапе с данным классом у Spring возникнет проблема: он не может создать этот класс из-за отсутствия публичного конструктора. Однако @Autowired применим не только к полям, но и к конструкторам, поэтому стоит просто переместить аннотацию на конструктор (и даже более того - если достать из контейнера AutowireCapableBeanFactory, то можно вручную создавать любые классы, у которых в конструкторе указаны присутствующие в контейнере зависимости).

3
  • Не могу понять, почему проект запускался, а после переустановки ОС нет. 2 окт 2015 в 14:26
  • @АндрійДзигар я не знаю, но не понимаю, почему он до этого запускался. Вы точно не меняли версии зависимостей в промежутке между запусками?
    – etki
    2 окт 2015 в 15:40
  • Ничего не менял. Залил проект на GitHub, поменял ОС с Вин7 на Ubuntu. Встановил все необходимое и скопировал проект с GitHub. Проект запустился. Но поставил корявий Ubuntu и пришлось переустановлять. После этого сделал все тоже самое. Проек не запустился. 2 окт 2015 в 20:16

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.