(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){
......
}
}
When you have more than one class you can do two things:
Use @Qualifier
annotation 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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With