其他类型的依赖注入

往谁里面注入就在谁里面定义变量以及set方法

1.普通数据类型的注入

xml文件中

 <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
 	<property name="username" value="zhangsan"/>
 	<property name="age" value="18"/>
 </bean>

UserDaoImpl类中

public class UserDaoImpl implements UserDao {
    
    
	  private String username;
      private int age;
      public void setUsername(String username) {
    
    
        	this.username = username;
      }
	   public void setAge(int age) {
    
    
	    	this.age = age;
	   }
}

     xml文件中的property标签表示,将username=zhangsan,传入到setUsername方法中将age=18,传入到setAge方法中。

2.引用数据类型的注入

     引用数据的注入其实就是之前发过的将Dao层注入到Service层的过程。

3.集合数据类型的注入

xml文件中

 <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
        <property name="strList">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
                <value>ddd</value>
            </list>
        </property>
        <property name="userMap">
            <map>
                <entry key="u1" value-ref="user1"></entry>
                <entry key="u2" value-ref="user2"></entry>
            </map>
        </property>
        <property name="properties">
            <props>
               <prop key="p1">ppp1</prop>
               <prop key="p2">ppp2</prop>
               <prop key="p3">ppp3</prop>
            </props>
        </property>
    </bean>
    
   <bean id="user1" class="com.itheima.domain.User">
        <property name="name" value="tom"/>
        <property name="addr" value="beijing"/>
    </bean>

    <bean id="user2" class="com.itheima.domain.User">
        <property name="name" value="lucky"/>
        <property name="addr" value="tianjin"/>
    </bean>

实现类中

public class UserDaoImpl implements UserDao {
    
    
    private Map<String, User> userMap;
    private List<String> strList;
    private Properties properties;

    public void setUserMap(Map<String, User> userMap) {
    
    
        this.userMap = userMap;
    }

    public void setStrList(List<String> strList) {
    
    
        this.strList = strList;
    }

    public void setProperties(Properties properties) {
    
    
        this.properties = properties;
    }
}

     xml文件中,表示将元素包含aaa,bbb,ccc,ddd的strList当作参数,传递给setStrList方法中;第二个表示将元素包含u1-user1,u2-user2的userMap当作参数,传递给setUserMap方法中,因为user1,user2是标签的id,所以需要value-ref;第三个表示将properties作为参数传入到setProperties方法中。

猜你喜欢

转载自blog.csdn.net/weixin_51656756/article/details/121178551