级联属性赋值
在的子元素中,为它所依赖的Bean的属性进行赋值,这就是所谓的”级联属性赋值”。
使用级联属性赋值注意事项:
- java类中必须有setter方法
- java类中必须有无参构造器(默认存在)
- 依赖其他Bean的类中,必须提供一个它依赖的Bean的getXxx()方法
Spring在Bean与Bean之间建立依赖关系的行为成为装配。Spring的IOC容器虽然强大,但本身不过是一个空壳,需要主动将Bean放进去,并告诉它Bean和Bean之间的依赖关系,才能按照我们的要求完成装配工作。
spring通过注解实现自动装配的步骤如下:
1.引入依赖
2.开启组件扫描
Spring默认不使用注解装配Bean。因此在Spring XML配置中,通过元素开启Spring Beans的自动扫描功能,即在类上使用了@Component注解,就将该类装配到容器中。
1 2 3 4 5 6 7 8 9 10 11 12
| <?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。
4.基于注解方式实现依赖注入