简体   繁体   中英

Spring Boot - are single implementing classes automatically injected

I am relatively new to Spring in general but have read through the Apress Spring Rest text and gotten the examples running in Eclipse without problem.

Something that puzzles me in the examples is how objects appear to be automatically injected. For example in chapter 8 security there is a QuickPollUserDetailsService class which implements the spring UserDetailsService class.

The text says the following:

"The SecurityConfig class declares a userDetailsService property, which gets injected with a QuickPollUserDetailsService instance at runtime."

@Configuration
@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter 
{        
@Inject
        private UserDetailsService userDetailsService;        
@Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.userDetailsService(userDetailsService)                        .passwordEncoder(new BCryptPasswordEncoder());        
}}

Nowhere in any file does it specify QuickPollUserDetailsService is to be set. Is Spring being smart here and noticing that QuickPollUserDetailsService is the only implementer of UserDetailsService and therefore assuming that it must be injected? If that is the case what if I had 2 or more implementer's of UserDetailsService

By default, Spring Boot will recursively scan the packages and available implementation will be automatically injected. If there is more than one implementation available, startup will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM