@Autowired原理

发布于:2022-12-13 ⋅ 阅读:(357) ⋅ 点赞:(0)

@Autowired

用来替代

<property name=""></property>

源码: 

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
目标:
        CONSTRUCTOR           构造方法
        METHOD                普通方法
        PARAMETER             参数
        FIELD                 字段
        ANNOTATION_TYPE       注解
@Retention(RetentionPolicy.RUNTIME)

通过看源码,我们可以看到,Autowired注解可以应用在构造方法,普通方法,参数,字段,以及注解这五种类型的地方,它的保留策略是在运行时。

原理:

        向spring容器中查找对应类型的JavaBean,通过set方法注入给属性

含义:

    自动装配,装配JavaBean,按照类型,通过set方法进行装配,set方法可以省略

位置:

    修饰成员变量

语法:

    @Autowired(属性名="属性值")

注意:     

    1.此注解按照类型装配

    2.按照类型装配,容器中必须有一个类型与之匹配,如果没有类型可以匹配,则会报异常

            NoSuchBeanDefinitionException 没有一个与之匹配

    3.按照类型装配,容器中如果有多个类型与之匹配,则会自动切换为按照名称装配,如果没有,则会报异常

            NoUniqueBeanDefinitionException 没有唯一一个与之匹配

例:

@Repository
public class StudentDaoImp implements IStudentDao {
    public void save() {
        System.out.println("======dao新增方法=======");
    }
}
@Service
public class StudentServiceImp implements IStudentService {
    @Autowired
    private IStudentDao dao;
    public void save() {
        System.out.println("========service新增方法============");
        dao.save();
    }
}
public class Test01 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        IStudentService service = (IStudentService) applicationContext.getBean("studentServiceImp");
        service.save();
    }
}

输出结果为: 

如果容器中没有一个与之相匹配的,则会报 NoSuchBeanDefinitionException

容器中如果有多个类型与之匹配,则会自动切换为按照名称装配

@Repository
public class StudentDaoImp implements IStudentDao {
    public void save() {
        System.out.println("======dao新增方法=======");
    }
}


@Repository
public class StudentDaoImp1 implements IStudentDao {
    public void save() {
        System.out.println("======dao1新增方法=======");
    }
}


@Service
public class StudentServiceImp implements IStudentService {
    @Autowired
    private IStudentDao studentDaoImp1;
    public void save() {
        System.out.println("========service新增方法============");
        studentDaoImp1.save();
    }
}

输出结果:

如果没有,则会报异常 NoUniqueBeanDefinitionException

 


网站公告

今日签到

点亮在社区的每一天
去签到