简体   繁体   中英

Dependency injection, delayed injection praxis

A simple(and lengthy) question, and not a simple answer. Working with some DI frameworks(Spring, Guice) I came to a conclusion that some of the praxis presented by others is not so simple to implement. I really seem stuck on this level.

I will try to present this as simple as possible, even though some of the details will probably be lost. I hope the question will be clear.

Say I have a StringValidator, a simple class with a responsibility to validate strings.

package test;

import java.util.ArrayList;
import java.util.List;

public class StringValidator {
    private final List<String> stringList;
    private final List<String> validationList;

    private final List<String> validatedList = new ArrayList<String>();

    public StringValidator(final List<String> stringList, final List<String> validationList) {
        this.stringList = stringList;
        this.validationList = validationList;
    }

    public void validate() {
        for (String currentString : stringList) {
            for (String currentValidation : validationList) {
                if (currentString.equalsIgnoreCase(currentValidation)) {
                    validatedList.add(currentString);
                }
            }
        }
    }

    public List<String> getValidatedList() {
        return validatedList;
    }
}

The dependency is the lowest possible, allowing simple tests like these:

package test;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class StringValidatorTest {
    @Test
    public void testValidate() throws Exception {
        //Before
        List<String> stringList = new ArrayList<String>();
        stringList.add("FILE1.txt");
        stringList.add("FILE2.txt");

        final List<String> validationList = new ArrayList<String>();
        validationList.add("FILE1.txt");
        validationList.add("FILE20.txt");

        final StringValidator stringValidator = new StringValidator(stringList, validationList);

        //When
        stringValidator.validate();

        //Then
        Assert.assertEquals(1, stringValidator.getValidatedList().size());
        Assert.assertEquals("FILE1.txt", stringValidator.getValidatedList().get(0));
    }
}

If we wanted to increase the flexibility even more, we could use Collection<> instead of List<>, but let's presume that that won't be necessary.

The classes that create the lists are the following(use any other interface standard):

package test;

import java.util.List;

public interface Stringable {
    List<String> getStringList();
}

package test;

import java.util.ArrayList;
import java.util.List;

public class StringService implements Stringable {

    private List<String> stringList = new ArrayList<String>();

    public StringService() {
        createList();
    }

    //Simplified
    private void createList() {
        stringList.add("FILE1.txt");
        stringList.add("FILE1.dat");
        stringList.add("FILE1.pdf");
        stringList.add("FILE1.rdf");
    }

    @Override
    public List<String> getStringList() {
        return stringList;
    }
}

And:

package test;

import java.util.List;

public interface Validateable {
    List<String> getValidationList();
}

package test;

import java.util.ArrayList;
import java.util.List;

public class ValidationService implements Validateable {

    private final List<String> validationList = new ArrayList<String>();

    public ValidationService() {
        createList();
    }

    //Simplified...
    private void createList() {
        validationList.add("FILE1.txt");
        validationList.add("FILE2.txt");
        validationList.add("FILE3.txt");
        validationList.add("FILE4.txt");
    }

    @Override
    public List<String> getValidationList() {
        return validationList;
    }
}

And we have a Main class with a main method:

package test;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        Validateable validateable = new ValidationService();
        final List<String> validationList = validateable.getValidationList();

        Stringable stringable = new StringService();
        final List<String> stringList = stringable.getStringList();

        //DI
        StringValidator stringValidator = new StringValidator(stringList, validationList);
        stringValidator.validate();

        //Result list
        final List<String> validatedList = stringValidator.getValidatedList();
    }
}

So let's say that the classes generate the lists in runtime(when the user wants to). The "direct"(static) binding is impossible.

If we want to provide the lowest possible coupling, we would use the lists to provide us with data required to run the validation(StringValidator).

BUT, if we want to use the container to help us with the "glue code", we could inject the two "services" into the StringValidator. That would provide us with the correct data, but at the cost of COUPLING. Also, StringValidator would have the extra responsibility of actually calling the dependencies.

If I use delegation in that way, I clutter my code with unwanted responsibilites(not something I want).

If I don't, I don't see a way in wich this could work(Provider could provide me with the correct lists, but, again, the dependency is there).

The more generic question is - is there a way to actually create a completly decoupled application using DI frameworks, or is this some sort of an ideal? In wich situations do you use the DI framework, in wich you don't? Are DI frameworks really the "new new"?

Thank you.

This is a somewhat difficult question to answer, especially because it's a contrived example, but if we assume that your classes are already designed exactly as you want them, the correct application of dependency injection here is simple. You seem to be focused on the testability of your StringValidator and on trying to do something magic to it with dependency injection. Where you should be concerned about testability is in your Main class. That's where you've introduced tight coupling and untestable code, and it's where a DI container will show its value. Proper application of DI and IoC principles might result in something like this instead:

public class Main {
    @Autowired
    private Validateable validateable;
    @Autowired
    private Stringable stringable;

    public void main() {
        final List<String> validationList = validateable.getValidationList();
        final List<String> stringList = stringable.getStringList();
        StringValidator stringValidator = new StringValidator(stringList, validationList);
        stringValidator.validate();
        final List<String> validatedList = stringValidator.getValidatedList();
    }

    public static void main(String[] args) {
        Container container = new ...;
        container.get(Main.class).main();
    }
}

In other words, all of your manual wiring just gets turned over to the control of the DI container. That's the whole point. Personally, I wouldn't be happy with this because you still have something that looks like a "component" class--the StringValidator--being instantiated by your code. I would look at ways to redesign things to get rid of this hard dependency in your code and turn that creation over to the container as well.

As for this "new new", no, DI containers aren't new. They've been around for quite a while. If you mean, "Should I use one?", then I guess my answer would be generally "yes", though the pattern is more important than any particular implementation. The benefits are well established and accepted, and it's more a way of thinking than an actual framework. As I've just demonstrated, your Main class was in essence a primitive DI container.

Update: If your primary concern is how to deal with the inputs to your StringValidator, there are a couple of options. There's no reason your "stringList" and "validationList" can't be managed by a DI container and injected into your StringValidator. Then the source of those lists is up to the container. They could come from your other objects or be injected by a test. Alternately, maybe you're looking to change the abstraction around how your StringValidator gets its inputs? In that case, maybe something like this will better suit your needs:

public class StringValidator {
    private SourceOfStrings stringSource;
    private SourceOfStrings validationStringSource;

    private final List<String> validatedList = new ArrayList<String>();

    ...

    public void validate() {
        for (String currentString : stringSource.getStrings()) {
            for (String currentValidation : validationStringSource.getStrings()) {
                if (currentString.equalsIgnoreCase(currentValidation)) {
                    validatedList.add(currentString);
                }
            }
        }
    }

    public List<String> getValidatedList() {
        return validatedList;
    }
}

interface SourceOfStrings {
    List<String> getStrings();
}

Note: NOT thread-safe. In a threaded environment, I would definitely go an extra step to remove the need to store the result in a field and call an extra method call to get it.

I am a little confused, but is what you mean you want to use DI without depending on any classes? This might be possible with annotations or a custom class loader, but it would be slow and incredibly hard to do. Maybe you could clarify what you wanted?

I finally think I got it! Sorry for the lack of information in my question. Ryan Stewart wrote "There's no reason your "stringList" and "validationList" can't be managed by a DI container and injected into your StringValidator.", and maybe he had this in mind. If you did, than that was the answer I was looking for, and your answer is correct, so thank you. I found it myself by experimenting in Spring.

If I use the classes that contain the lists, than the resulting class cannot recive the lists. They are dynamically created, and I saw no way to bring them to StringValidator. Dynamically means - without the control of the container.

The only way I could have injeted them was to inject them directly into StringValidator.

But I forgot one thing. Spring is much more flexibile(based on my experience) - I frankly don't know how I could have solved this in Guice(haven't really tried, maybe I'll give it a go).

Why not create the list dynamically, and use that list in the container life as a list that can be used to inject the required class?

在此处输入图片说明

The point being, when the container initializes the list:

package test;

import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class StringList extends ArrayList<String> {
}

package test;

import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class ValidationList extends ArrayList<String> {
}

Or if you prefer the xml way(commented):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <context:component-scan base-package="test"/>

    <!--<bean id="validationList" class="java.util.ArrayList" scope="singleton"/>-->
    <!--<bean id="stringList" class="java.util.ArrayList" scope="singleton"/>-->
</beans>

That list can be used throught the life of the container, thus the application.

package test;

import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Component
public class StringService implements Stringable {

    private List<String> stringList;

    @Inject
    public StringService(final ArrayList<String> stringList) {
        this.stringList = stringList;
        createList();
    }

    //Simplified
    private void createList() {
        stringList.add("FILE1.txt");
        stringList.add("FILE1.dat");
        stringList.add("FILE1.pdf");
        stringList.add("FILE1.rdf");
    }

    @Override
    public List<String> getStringList() {
        return stringList;
    }
}

package test;

import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Component
public class ValidationService implements Validateable {

    private List<String> validationList;

    @Inject
    public ValidationService(final ArrayList<String> validationList) {
        this.validationList = validationList;
        createList();
    }

    //Simplified...
    private void createList() {
        validationList.add("FILE1.txt");
        validationList.add("FILE2.txt");
        validationList.add("FILE3.txt");
        validationList.add("FILE4.txt");
    }

    @Override
    public List<String> getValidationList() {
        return validationList;
    }
}

And, I don't have to worry about the services, because the lists are now in the container, living their own lifecycle, thus available every time i request them.

package test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StringValidator {
    private List<String> stringList;
    private List<String> validationList;

    private final List<String> validatedList = new ArrayList<String>();

    @Autowired
    public StringValidator(final ArrayList<String> stringList,
                           final ArrayList<String> validationList) {
        this.stringList = stringList;
        this.validationList = validationList;
    }

    public void validate() {
        for (String currentString : stringList) {
            for (String currentValidation : validationList) {
                if (currentString.equalsIgnoreCase(currentValidation)) {
                    validatedList.add(currentString);
                }
            }
        }
    }

    public List<String> getValidatedList() {
        return validatedList;
    }
}

The answer actually looks very simple, but it took me some time before I could get here.

So, the Main class looks like this, and everything is handeled by the container.

package test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class Main {
    @Autowired
    private StringValidator stringValidator;

    public void main() {
        stringValidator.validate();
        final List<String> validatedList = stringValidator.getValidatedList();
        for (String currentValid : validatedList) {
            System.out.println(currentValid);
        }
    }

    public static void main(String[] args) {
        ApplicationContext container = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");
        container.getBean(Main.class).main();
    }
}

It seems possible. So to recap the answer - you could always have the dynamically created class in the container, and a pretty good decoupleing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM