- Spring项目基础的环境配置
1.1 创建需要spring代理的实体类
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", info=" + info +
'}';
}
}
1.2 创建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="student" class="cn.spr.pojo.Student">
<property name="name" value="李华"></property>
</bean>
</beans>
1.3 运行程序中引用实体
@Test
public void test01(){
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
- set注入不同类型的数据
<?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="addr" class="cn.spr.pojo.Address">
<property name="address" value="上海"></property>
</bean>
<bean id="student" class="cn.spr.pojo.Student">
<!--1.普通常量注入-->
<property name="name" value="李华"></property>
<!--2.引用注入-->
<property name="address" ref="addr"></property>
<!--3.数组注入-->
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
</array>
</property>
<!--4.List注入-->
<property name="hobbies">
<list>
<value>123</value>
<value>4567</value>
</list>
</property>
<!--5.Map集合注入-->
<property name="card">
<map>
<entry key="身份证" value="4256272"></entry>
<entry key="手机" value="118828"></entry>
</map>
</property>
<!--6.properties注入-->
<property name="info">
<props>
<prop key="学号">1123</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>