over 3 years ago

有時候不小心疏忽了就會無法注入,所以紀錄一下

大部分的時候設計都會像是工廠模式,但是使用的方式不同要小心注入的對象而有差異

如果是像下面用抽象類別來注入

BaseService.java
/**
 * 
 * @author samzhu
 *
 * @param <T> 實體物件
 * @param <ID> ID類型 ex:String,Long,Integer
 */
public abstract class BaseService<T,ID extends Serializable> {
    public abstract int save(T record);
    public abstract int update(T record);
    public abstract int updateOrReplace(T record);
    public abstract T get(ID id);
}

那只需要標記@Service,直接引用即可自動注入

TokenmanaService.java
@Service
public class TokenmanaService extends BaseService<Tokenmana,String>{
    
    @Autowired
    private TokenmanaMapper tokenmanaMapper;

    @Override
    public int save(Tokenmana record) {
        return tokenmanaMapper.insert(record);
    }

    @Override
    public int update(Tokenmana record) {
        record.setTimeupdate(new Date(System.currentTimeMillis()));
        return tokenmanaMapper.updateByPrimaryKey(record);
    }

    @Override
    public int updateOrReplace(Tokenmana record) {
        return tokenmanaMapper.updateByPrimaryKey(record);
    }

    @Override
    public Tokenmana get(String tokenid) {
        Tokenmana tokenmana = tokenmanaMapper.selectByPrimaryKey(tokenid);
        return tokenmana;
    }
@Autowired
private TokenmanaService tokenmanaService;

如果是用介面來定義工廠

BaseServiceInterface.java
public interface BaseServiceInterface<T,ID extends Serializable> {
    public int save(T record);
    public int update(T record);
    public int updateOrReplace(T record);
    public T get(ID id);
}

那必須給元件名稱

TokenmanaServiceImpl.java
@Component("tokenmanaServiceImpl")
public class TokenmanaServiceImpl implements BaseServiceInterface<Tokenmana,String>{
    
    @Autowired
    private TokenmanaMapper tokenmanaMapper;
    
    @Override
    public int save(Tokenmana record) {
        return tokenmanaMapper.insert(record);
    }
    
    @Override
    public int update(Tokenmana record) {
        // TODO Auto-generated method stub

        return 0;
    }

    @Override
    public int updateOrReplace(Tokenmana record) {
        // TODO Auto-generated method stub

        return 0;
    }

    @Override
    public Tokenmana get(String id) {
        // TODO Auto-generated method stub

        return null;
    }
}

好方便注入時讓框架知道是哪個元件,因為是要注入到interface,這個要注意

@Autowired @Qualifier("tokenmanaServiceImpl")
private BaseServiceInterface tokenmanaService;
← 使用Spring-Boot快速建構Web應用 Spring注入設定檔的方式 →
 
comments powered by Disqus