国王陛下万万岁

导航

 

 

1.构造器注入引用类型

第一步,在类的构造方法中调用引用类型,如下的构造方法:public BookServiceImpl(BookDao bookDao1)

Java Bean

package com.oxygen.service.impl;

import com.oxygen.dao.BookDao;
import com.oxygen.service.BookService;

public class BookServiceImpl implements BookService {
    private BookDao bookDao;


    //这是构造器注入引用类型
    public BookServiceImpl(BookDao bookDao1){
        this.bookDao=bookDao1;
    }


    //此类当中没有setter方法
    public void save() {
        System.out.println("Book Service save...");
        bookDao.save();
    }
}

 

第二步,在xml配置文件中配置:

 <bean id="bookService" name="service service2" class="com.oxygen.service.impl.BookServiceImpl">
      <constructor-arg name="bookDao1" ref="bookDao"/>
    </bean>

 

2.构造器注入简单类型类型

第一步,在类的构造方法中调用引用类型,如下的构造方法:public BookServiceImpl(BookDao bookDao1)

Java Bean

package com.oxygen.dao.impl;

import com.oxygen.dao.BookDao;

public class BookDaoImpl implements BookDao{

    private String userName;
    private int userId;

    //构造器注入简单类型
    public BookDaoImpl(String userName, int userId) {
        this.userName = userName;
        this.userId = userId;
    }

    public void save() {
        System.out.println("Book Dao Save...");
        System.out.println("User Name:"+userName);
        System.out.println("User ID:"+userId);
    }

}

 

第二步,在xml配置文件中配置:

<bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl" >
        <constructor-arg name="userName" value="周杰无与伦比"/>
        <constructor-arg name="userId" value="2022100102"/>
    </bean>

 

前一篇:

Spring的依赖注入两种方式之一:setter注入

posted on 2022-10-16 18:53  国王陛下万万岁  阅读(284)  评论(0编辑  收藏  举报