spring-自动装配
bean的自动装配
1.自动装配是spring满足bean的方式
2.spring会自动在上下文中寻找,并自动装配属性
一共有三种方式:
1.在xml中显示配置
2.在Java中显示自动装配
3.隐式的自动装配
测试
1.环境搭建
2.byname:
<bean id="people" class="com.zhang.pojo.People" autowire="byName">
<property name="name" value="zhang"/>
3.bytype:
<!--bytype:会自动在容器上下文中查找与自己属性相同的Bean,可以不需要id-->
<bean id="people" class="com.zhang.pojo.People" autowire="byType">
<property name="name" value="zhang"/>
</bean>
4.使用注解
注解须知:
1.导入约束context约束
2.配置注解支持:** context:annotation-config/**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Autowired
直接在属性上面使用,也可以直接在set上面使用,使用时可以不用set方法
科普:


小结
@Resource和@Autowired区别:
1.都是自动装配
2.都可以放在属性上面
3.@Resource通过byname实现,对象必须存在
4.@Autowired通过byname实现如果找不着名字,则通过bytype实现
浙公网安备 33010602011771号