简体   繁体   中英

Spring dependency injection - best design pattern of configuration

Right now i have a inherited project that is using annotation based spring dependency injection. So all classes are simply marked with @Component (or specific stereoTypes like @service, @Repository,@RestController, etc). This makes it a little hard to find where the dependency is located and i was thinking to change it so that each package has its own dependency configuration and then add each package to the @ComponentScan afterwards.

So for example if i had a package called com.mycoolpackage.login and mycoolpackage.networking then i'd have a Spring configuration like this in first package:

 @Configuration

    public class LoginDIConfig {

        @Bean
        public LoginServiceImpl loginServiceImpl() {
            return new LoginServiceImpl();
        }

    }

and in the second package i'd have the following:

@Configuration

public class NetworkDIConfig {

    @Bean
    public NetworkServiceImpl networkServiceImpl() {
        return new NetworkServiceImpl();
    }

}

and my@ComponentScan would look like this:

@ComponentScan(basePackages = {"com.mycoolpackage.login","com.mycoolpackage.network"}) 

So i have two questions about this approach.

  1. How can i use a @Service annotation instead of bean here
  2. Do you think this design is more easier as it tells you what your package dependencies are very easily instead of hunting them down.

If you want to configure some been properties manually then you should go for above configuration else you should stick with exiting one.

This makes it a little hard to find where the dependency is located

@Autowire Or @Inject annotation will always lead you to dependency class.

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