一. Set注入
【环境搭建】
复杂类型
//使用了lombok插件直接生成get,set等方法
@Data
public class Address {
private String address;
}
真实测试对象
//使用了lombok插件直接生成get,set等方法
@Data
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> gams;
private String wife;
private Properties info;
}
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">
<bean id="address" class="com.randy.pojo.Address">
<property name="address" value="广东"/>
</bean>
<bean id="student" class="com.randy.pojo.Student">
<property name="name" value="Randy"/>
<property name="address" ref="address"/>
<property name="books">
<array>
<value>西游记</value>
<value>三国演义</value>
<value>水浒传</value>
</array>
</property>
<property name="hobbys">
<list>
<value>唱歌</value>
<value>敲代码</value>
</list>
</property>
<property name="card">
<map>
<entry key="姓名" value="恒哥"/>
<entry key="性别" value="男"/>
<entry key="年龄" value="22"/>
</map>
</property>
<property name="gams">
<set>
<value>魂斗罗</value>
<value>雪人兄弟</value>
</set>
</property>
<property name="wife">
<null/>
</property>
<property name="info">
<props>
<prop key="水果">苹果</prop>
<prop key="饮料">奶茶</prop>
</props>
</property>
</bean>
</beans>
测试方法
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
二、拓展方式注入
可以用p命令和c命令进行注入
测试类:
//使用了lombok插件直接生成get,set等方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
使用方法:
<?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">
<bean id="user" class="com.randy.pojo.User" p:name="Randy1" p:age="18"/>
<bean id="user2" class="com.randy.pojo.User" c:name="Randy2" c:age="22"/>
</beans>
p命令:本质是property,需要用到无参构造方法创建和set方法赋值
c命令:本质是constructor-arg,需要用到有参构造方法直接创建
测试方法:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
注意:p命令和c命令不能直接使用,需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"