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