基于XML的属性装配
1、手动装配
<!-- 属性的装配:手动装配 -->
<bean id="userService" class="com.neuedu.spring.bean.UserService"></bean>
<bean id="userAction" class="com.neuedu.spring.bean.UserAction">
<property name="userService" ref="userService"></property>
</bean>
2、自动装配
1.按类型装配:byType
首先检测当前bean中需要装配的属性的类型
然后在IOC容器中查找匹配这个类型的bean
如果类型匹配的bean是唯一的,那么就将这个匹配的bean注入到userAction中
<bean id="userService" class="com.neuedu.spring.bean.UserService"></bean>
<bean id="userAction" autowire="byType" class="com.neuedu.spring.bean.UserAction"></bean>
2.按bean的id值装配:byName
首先检测当前bean中需要装配的属性的属性名,属性名是将setXxx()方法去掉set,首字母小写得到的
然后根据属性名作为id的值,在IOC容器中查找对应的bean
如果能够找到,则将找到bean注入进去
3、自动装配示例:
UserAction类:
public class UserAction {
private User user; public User getUser() {
return user;
} public void setUser1(User user) {
this.user = user;
}
}
ApplicationContext配置:
<bean id="user1" class="com.neuedu.spring.bean.User">
<property name="username" value="张三"></property>
</bean>
<bean id="userAction" class="com.neuedu.spring.bean.UserAction" autowire="byName"></bean>
测试代码:
@Test
public void test24() throws Exception {
ApplicationContext ioc=new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserAction bean = ioc.getBean(UserAction.class);
System.out.println(bean.getUser().getUsername());
}
输出结果张三,证明byName是通过将setXxx()方法去掉set,首字母小写得到的属性名进行注入的