Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if there are more than one classes implementing one interface ,then how does @autowired work? [duplicate]

(spring mvc)first i do not know whether the writing below are right or not.if it is right ,then i don't understand how the @autowired works here.if it is wrong , then how i should do when i have more than one classes to implement one interface.

public interface UserDao{
    public User findUserByUserName(String username);
}

public class UserDaoImpl1 implements UserDao{

    @Override
    public User findUserByUserName(String username){
            .......
    }
}

public class UserDaoImpl2 implements UserDao{
    @Override
    public User findUserByUserName(String username){
            .......
    }
}

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;//how does atuowired work here?

    @Override
    public User loginCheck(User user){
                ......
        }
}
like image 379
lhao0301 Avatar asked Mar 22 '15 09:03

lhao0301


1 Answers

When you have more than one class you can do two things:

  1. Use @Qualifierannotation and tell which implementation should be injected (spring default qualifier is name of bean) so doing this will inject second bean implementation:

    @Autowired
    @Qualifier("userDaoImpl2")
    private UserDao userDao;
    
  2. You can use @Primary on beans so that one implementation would be always preferred over another when there are more than one and interface is @Autowire.

Choice can be made based on side which should know about autowiring, if you want classes which are injected with dependencies to be ease to change and unaware of implementation details you should go with option 2 and if you want to control dependencies option 1 is better choice.

If more than one option exists Spring should throw exception (so your code should throw exception telling you more than one candidate for autowiring exists). It should look like:

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.package.name.UserDao] is defined: expected single matching bean but found 2: [userDaoImpl1, userDaoImpl2]

Here is good link that explains details.

like image 141
Nenad Bozic Avatar answered Nov 11 '22 04:11

Nenad Bozic