spring的装配方式:
(1)手动装配
<?xml version="1.0" encoding="UTF-8"?><beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id="cat" > <property name="voice" value="mom~"/> </bean> <bean id="dog" > <property name="voice" value="wow~"/> </bean> <bean id="people" > <property name="name" value="tata"/> <property name="dog" ref="dog"/> <property name="cat" ref="cat"/> </bean></beans>(2)自动装配
通过byName自动装配
<bean id="people" autowire="byName"> <property name="name" value="tata"/></bean>通过byType自动装配
<bean id="people" autowire="byType"> <property name="name" value="tata"/></bean>(3)使用注解实现自动装配
使用之前导入注解依赖的配置和支持
<?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>不再使用显示引用对象依赖的其他属性
<bean id="cat" /><bean id="dog" /><bean id="people" />@Autowired
直接在对象上面使用@Autowired注解
private String name;@Autowiredprivate Dog dog;@Autowiredprivate Cat cat;如果装配环境复杂的话,可以通过@Qualifier(value = "cat")指定bean注入
例如多个cat对象bean,属性值不同的时候
<bean id="cat" > <property name="eat" value="fish"/></bean><bean id="cat11" > <property name="eat" value="cookie"/></bean>就需要
@Qualifier
否则,只会spring会走第一个bean
@Autowired@Qualifier(value = "cat11")private Cat cat;Resource
@Resource(name="cat")private Cat cat;