1.注入方式
其中,ref为引用其他bean,value是普通属性的注入。
先来看看set方法:
<bean id="Service" class="com.demo.impl.ServiceImpl" >
<property name="id" value="001"></property>
<property name="userdaoimpl" ref="UserDao"></property>
</bean>
<bean id="UserDao" class="com.demo.impl.UserDaoImpl"></bean>
public class ServiceImpl implements Service{
public void setId(int id) {
System.out.println("set方法,普通参数");
}
public void setUserdaoimpl(UserDaoImpl userdaoimpl) {
System.out.println("set方法,引用其他bean");
}
}
输出结果
再来看看构造方法:
public class ServiceImpl implements Service{
public ServiceImpl(String id, UserDaoImpl userdaoimpl) {
System.out.println("构造方法,普通参数和引用其他bean");
}
}
<bean id="Service" class="com.demo.impl.ServiceImpl" >
<constructor-arg name="id" value="001"></constructor-arg>
<constructor-arg name="userdaoimpl" ref="UserDao"></constructor-arg>
</bean>
<bean id="UserDao" class="com.demo.impl.UserDaoImpl"></bean>
输出结果:
2. 注入数据类型
-
普通数据类型。如int,String等,通过value属性指定
-
引用数据类型。如ServiceImpl,UserDaoImpl等,通过ref属性指定
-
集合数据类型。如set,map,List,properties等
这里就主要再讲一下集合数据(List)怎么去注入:
public class ServiceImpl implements Service{ //举两种List类型 public List<String> stringList; public List<UserDaoImpl> userDaoList; public void setStringList(List<String> stringList) { this.stringList = stringList; } public void setUserDaoList(List<UserDaoImpl> userDaoList) { this.userDaoList = userDaoList; } public void show(){ System.out.println(stringList); System.out.println(userDaoList); } }
<bean id="Service" class="com.demo.impl.ServiceImpl" > <property name="stringList"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> <property name="userDaoList"> <list> <bean class="com.demo.impl.UserDaoImpl"></bean> <bean class="com.demo.impl.UserDaoImpl"></bean> <bean class="com.demo.impl.UserDaoImpl"></bean> </list> </property> </bean> <bean id="UserDao" class="com.demo.impl.UserDaoImpl"></bean> //关于userDaoList,还可以这样配 <property name="userDaoList"> <list> <ref bean="UserDao1"></ref> <ref bean="UserDao2"></ref> <ref bean="UserDao3"></ref> </list> </property> </bean> <bean id="UserDao1" class="com.demo.impl.UserDaoImpl"></bean> <bean id="UserDao2" class="com.demo.impl.UserDaoImpl"></bean> <bean id="UserDao3" class="com.demo.impl.UserDaoImpl"></bean>
输出结果:
同理,其他集合都是类似的操作。
标签:依赖,Spring,ServiceImpl,List,System,bean,userDaoList,public,out From: https://blog.csdn.net/Ggjvhsjsj/article/details/142787729