依赖注入和自动装配的区别与联系
自动装配其实是依赖注入的升级版,为了简化依赖注入的配置而生成的
依赖注入的两种方式:
1,构造器注入
2,setter注入
1.构造器注入对象属性
<bean id="text" class="com.maven.Text" />
<bean id="hello" class="com.maven.Hello"><constructor-arg ref="text" /></bean>
2. 属性注入对象属性
<bean id="hello" class="com.maven.Hello"><property name="text" ref="text" /></bean>
自动装配的4中方式:
1,byName
2,byType
3,constructor
byName 一般使用注解@Resource 是java ee提供的包
byType 一般使用注解@Autowired 是spring提供的包,如果想要byName装配结合@Qualifier使用
@Autowired 是必须存在的,默认required=true
constructor 利用当前对象生成带参的构造方法
<!--注解驱动 -->
<context:annotation-config/>
context:component-scan除了具有context:annotation-config的功能之外,context:component-scan还可以在指定的package下扫描以及注册javabean 。还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。
因此当使用 context:component-scan 后,就可以将 context:annotation-config移除。