目录
- Spring中Bean的三种装配方式
- 在xml中显式配置
- 在java中显式配置
- 隐式的自动装配
- 使用xml配置实现自动装配
- byName 会自动在容器上下文中查找和set方法值名称相同的id的bean
- byType 会自动在容器上下文中查找和属性类型相同的bean
- 使用注解实现自动装配
- 导入约束
- 开启注解支持 context:annotation-config/
- @Autowired
- @Resource
- @Autowired和@Resource的区别
<bean id="cat" class="com.qing.pojo.Cat"/>
<bean id="person" class="com.qing.pojo.Person" autowire="byName">
<property name="name" value="张三丰"/>
</bean>
<bean class="com.qing.pojo.Cat"/>
<bean id="person" class="com.qing.pojo.Person" autowire="byType">
<property name="name" value="张三丰"/>
</bean>
jdk1.5开始支持注解,spring2.5开始支持注解
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/>
<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>
直接在属性上使用即可,也可以在set方法上使用
@Autowired
private Cat cat;