作用为给bean在容器中命名,多用在dao层
    定义一个接口

    1. public interface UserRepository {
    2. void save();
    3. }

    两个实现类

    1. package com.proc.bean.repository;
    2. import org.springframework.stereotype.Repository;
    3. //将此UserRepositoryImps类在容器中命名改为userRepository
    4. @Repository("userRepository")
    5. public class UserRepositoryImps implements UserRepository{
    6. @Override
    7. public void save() {
    8. System.out.println("UserRepositoryImps save");
    9. }
    10. }
    1. package com.proc.bean.repository;
    2. import org.springframework.stereotype.Repository;
    3. //这个实现类则不进行命名
    4. @Repository
    5. public class UserJdbcImps implements UserRepository {
    6. @Override
    7. public void save() {
    8. System.out.println("UserJdbcImps save");
    9. }
    10. }

    调用接口测试:

    1. @Autowired
    2. private UserRepository userRepository;
    3. //会找到我们命名为userRepository的bean,并装配到userRepository中