JAVA之自动装配

级联属性赋值

在<bean>的<property>子元素中,为它所依赖的Bean的属性进行赋值,这就是所谓的”级联属性赋值”。

使用级联属性赋值注意事项:

  1. java类中必须有setter方法
  2. java类中必须有无参构造器(默认存在)
  3. 依赖其他Bean的类中,必须提供一个它依赖的Bean的getXxx()方法

Spring在Bean与Bean之间建立依赖关系的行为成为装配。Spring的IOC容器虽然强大,但本身不过是一个空壳,需要主动将Bean放进去,并告诉它Bean和Bean之间的依赖关系,才能按照我们的要求完成装配工作。

spring通过注解实现自动装配的步骤如下:

1.引入依赖

2.开启组件扫描

Spring默认不使用注解装配Bean。因此在Spring XML配置中,通过元素开启Spring Beans的自动扫描功能,即在类上使用了@Component注解,就将该类装配到容器中。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <!--添加context相关的约束-->
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描功能-->
    <context:component-scan base-package="net.biancheng.c"></context:component-scan>
</beans>

3.使用注解定义Bean

Spring提供了多个注解,在不同类的层次下,使用不同的注解,将他们定义为Spring Bean。

图片[1]-JAVA之自动装配-TOY论坛

4.基于注解方式实现依赖注入

图片[2]-JAVA之自动装配-TOY论坛
© 版权声明
THE END
喜欢就支持以下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容