前言
Bean的装配可以理解为依赖关系注入,Bean的装配方式即Bean依赖注入的方式。Spring容器支持多种形式的Bean的装配方式,如基于XML的装配、基于注解(Annotation)的装配和自动装配(其中最常用的是基于注解的装配),本文章将主要讲解着三种装配方式的使用。
基于XML的装配
方式一:设置注入
条件:①Bean类必须有一个无参构造方法;②Bean类必须为属性提供setter方法。
在配置文件中,使用元素来为每个属性注入值
方式二:构造注入
条件:Bean类必须提供有参构造方法
在配置文件中,使用元素来为参数注入值
具体实现步骤如下
- 创建Java类User,提供有参、无参构造方法以及属性setter方法;
package com.ssm.assemble;
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
/**
* 1.使用构造注入
* 1.1提供带所有参数的有参构造方法。
*/
public User(String username, Integer password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
/**
* 2.使用设值注入
* 2.1提供默认空参构造方法 ;
* 2.2为所有属性提供setter方法。
*/
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password +
", list=" + list + "]";
}
}
- 创建Spring配置文件beans1.xml,使用以上两种方式装配Bean;
<?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-4.3.xsd">
<!--1.使用构造注入方式装配User实例 -->
<bean id="user1" class="com.ssm.assemble.User">