Skip to content

Instantly share code, notes, and snippets.

@dantonyuk
Last active July 15, 2020 16:44
Show Gist options
  • Save dantonyuk/0e48c5b5ea870fb6ba25bbc0b4611786 to your computer and use it in GitHub Desktop.
Save dantonyuk/0e48c5b5ea870fb6ba25bbc0b4611786 to your computer and use it in GitHub Desktop.

Multiple Beans with the Same Type

The Spring application has an interface

public interface UserService {
  // ...
}

with the only implementation

@Service
public class RegularUserService implements UserService {
  // ...
}

The application also contains one hundred services using UserService exactly the same way as it's shown below:

@Service
public class Service1 {
  @Autowired
  private UserService userService;

  // ...
}

@Service
public class Service2 {
  @Autowired
  private UserService userService;

  // ...
}

// ...

@Service
public class Service100 {
  @Autowired
  private UserService userService;

  // ...
}

You got an assignment to

  • implement one more UserService bean working with privileged users, let's call it PrivilegedUserService.
  • use PrivilegedUserService in only one service, let's say, Service100. All other services should continue to use good old RegularUserService.

You've done with the first part:

@Service
public class PrivilegedUserService implements UserService {
  // ...
}

How would you complete the second one?

Follow-up:

Can you do it with no touching the rest 99 services?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment