Spring-Bean的依赖注入的数据类型
Spring-Bean的依赖注入的数据类型
除了对象的引用可以注入,普通数据类型,集合等都可以在容器中进行注入
数据的三种数据类型
- 普通数据类型
- 引用数据类型
- 集合数据类型
普通数据类型
-
public class UserDaoImpl implements UserDao {
private String username;
private int age;public void setUsersname(String usersname) {
this.username = usersname;
}public void setAge(int age) {
this.age = age;
}
public void save() {
System.out.println(username);
System.out.println(age);
System.out.println("save running.....");
}
}
xml核心配置文件
<bean id="userDao" class="com.my.UserDaoImpl">
<property name="age" value="123"/>
<property name="usersname" value="zhangsan"/>
</bean>
<bean id="userService" class="com.my.service.UserImplService">
<!--这里的name是构造函数里面的参数userDao ref为容器中Bean的ID-->
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
测试
public class UserDemo {
@Test
public void mytest(){
ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userDao1 = (UserService) application.getBean("userService");
userDao1.save();
}
}
集合数据类型
private Properties properties;
set方法
public void setProperties(Properties properties) {
this.properties = properties;
}
xml配置文件
<bean id="userDao" class="com.my.UserDaoImpl">
<property name="properties">
<props>
<prop key="p1">pppp2</prop>
<prop key="p2">pppp3</prop>
<prop key="p3">pppp4</prop>
</props>
</property>
</bean>
引用数据类型之map
声明变量
private Map<String, User> userMap;
Map里面的set方法
package com.my.domain;
public class User {
private String name;
private String addr;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
MapXML配置文件(重点)
<bean id="userDao" class="com.my.UserDaoImpl">
<property name="userMap">
<map>
<!--第一个key为map的key-->
<entry key="u1" value-ref="user1"/>
<entry key="u2" value-ref="user2"/>
</map>
</property>
</bean>
<bean id="user1" class="com.my.domain.User">
<property name="name" value="qwertyu"/>
<property name="addr" value="beijing"/>
</bean>
<bean id="user2" class="com.my.domain.User">
<property name="name" value="qwj"/>
<property name="addr" value="luvy"/>
</bean>
测试
public class UserDemo {
@Test
public void mytest(){
ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userDao1 = (UserService) application.getBean("userService");
userDao1.save();
}
}
{{uploading-image-82062.png(uploading...)}}