- Spring的注入都是通过对象属性的set方法注入,或者是构造器注入
bean简单注入赋值,构造注入赋值
<!--第一种方式:通过下标赋值-->
<bean id="user1" class="cn.mao.pojo.User">
<constructor-arg index="0" value="maoshi"/>
<constructor-arg index="1" value="2"/>
</bean>
<!--第二种方式: 通过有参构造器创建对象 -->
<bean id="user" class="cn.mao.pojo.User">
<constructor-arg name="name" value="youshi"/>
<constructor-arg name="age" value="1"/>
</bean>
各种复杂数据类型注入
数组、对象、注入null、List、Map、Set、Properties
实体类
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private String wife;
private Properties info;
//.....set get 省略
}
beans.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--依赖注入 set方式注入
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入!
-->
<bean id="student" class="cn.mao.pojo.Student">
<!--普通值注入-->
<property name="name" value="youshi"/>
<!--对象/bean注入-->
<property name="address" ref="address"/>
<!--数组注入-->
<property name="books">
<array>
<value>java</value>
<value>mysql</value>
<value>python</value>
</array>
</property>
<!--List注入-->
<property name="hobbys">
<list>
<value>赚钱</value>
<value>代码</value>
</list>
</property>
<!--Map 注入-->
<property name="card">
<map>
<entry key="身份证" value="23411234123"/>
<entry key="学号" value="3453254"/>
</map>
</property>
<!--Null注入-->
<property name="wife">
<null/>
</property>
<!--Properties注入 文本文件-->
<property name="info" >
<props>
<prop key="user">youshi</prop>
<prop key="name">maoshi</prop>
<prop key="age">16</prop>
</props>
</property>
</bean>
<bean id="address" class="cn.mao.pojo.Address">
<property name="address" value="贵州"/>
</bean>
<!--导入另一个beans-->
<import resource="userBean.xml"/>
</beans>
使用命名空间注入
需要添加命名空间约束,才能使用命名注入
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
当然命名空间也可以注入对象,例如:p:name-ref="一个beanId"
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以注入属性值:property-->
<bean id="user" class="cn.mao.pojo.User" p:age="16" p:name="幼诗"/>
<!-- c命名空间注入 通过构造器注入 constructs;
scope="singleton" 单例模式
scope="prototype" 原型模式/多例模式
其余的模式:request、session、application 这些要在web项目才使用到
-->
<bean id="user2" class="cn.mao.pojo.User" c:age="999" c:name="猫屎" scope="prototype"/>
</beans>