Three ways of IOC dependency injection and their differences

constructor injection

The parameter list of dependent objects is declared in the construction method, so that the IoC container knows which dependent objects it needs.

This method is relatively intuitive. After the object is constructed, it enters the ready state and can be used immediately.

public FXNewsProvider(IFXNewsListener newsListner,IFXNewsPersister newsPersister)
{
    
    
    this.newsListener = newsListner;
    this.newPersistener = newsPersister; 
}

setter method injection (setter injection)

You only need to add a setter method to the attribute corresponding to the dependent object, and you can set the corresponding dependent object to the injected object through the setter method.

It is looser than constructor injection, and can be injected after the object construction is completed.

public class FXNewsProvider
{
    
    
    private IFXNewsListener newsListener;
    private IFXNewsPersister newPersistener;
    public IFXNewsListener getNewsListener() {
    
    
        return newsListener;
    }
    public void setNewsListener(IFXNewsListener newsListener) {
    
    
        this.newsListener = newsListener;
    }
    public IFXNewsPersister getNewPersistener() {
    
    
        return newPersistener;
    }
    public void setNewPersistener(IFXNewsPersister newPersistener) {
    
    
        this.newPersistener = newPersistener;
    }
}

interface injection

If the injected object wants the IoC Service Provider to inject dependent objects into it, it must implement an interface. This interface provides a method for injecting dependent objects into it. The IoC Service Provider finally uses these interfaces to understand what dependent objects should be injected into the injected object.

Interface injection is relatively rigid and cumbersome. It is a method that is not advocated now, and "retired" players.

Three ways to compare

injection method Advantages and disadvantages
constructor injection The advantage of construction method injection is that when the object is constructed, it can be in a ready state and can be used. The disadvantage is that if there are too many objects, or if the parameters of an object are many and complex, the construction method is very cumbersome, and the maintenance is also difficult. have greater difficulties
setter method injection It is mainly reflected in the aspect of performance, because the method can be customized, and the description is more humanized, and there can be default value settings. The disadvantage may be that the object cannot be used immediately
interface injection The intrusion is too strong. If the dependent object needs to be injected, the injected object must declare and implement another interface. This method is not advocated

Guess you like

Origin blog.csdn.net/weixin_42648692/article/details/129385655