Can I insert an object that is created dynamically

I have a question regarding dependency injection.

I have a class, say:

class MyClass {
    MyServiceAPI serviceAPI;
    public setSession(Session session) {
         serviceAPI = new MyServiceAPI(session);     
    }
    ....
}

A session is created by another class that loads it from the database at run time.

class MyAnotherClass {
    Myclass myClass;

    @Inject
    MyAnotherClass(MyClass myClass) {
        this.myClass = myClass;
    }

    public someFunction() {
        String key = <read from database>;
        Session session = new Session(key);
        myClass.setSession();
        ......
    }
}

As he described, an instance of MyClass is injected into MyAnotherClass, and a serviceAPI instance in MyClass is created using the new one. If I want to add the ServiceAPI to MyClass, maybe I will create it in the class where the session is created, and using the installer, set it to MyClass.

But the question is, I don't want MyAnotherClass to create MyServiceAPI and inject it into MyClass. I want MyAnotherClass not to expect MyServiceAPI to exist.

Is there a way to do this with a depdendency injector like Guice or Spring? Or just Java?

Many thanks.

+3
4

Java, Java 6 Java. jar .. Java SPI

+1

guice factory. MyServiceAPI .

public class MyClass {

    @Inject
    private MyServiceFactory factory;
    private MyServiceAPI myServiceAPI;

    public void setSession(Session session) {
        myServiceAPI = factory.createMyServiceAPI(session);
    }
}

public class MyServiceFactory {

    MyServiceAPI createMyServiceAPI(Session session) {
        // create with new, inject via Injector, do what you want... :)
        return <yourobject>;
    }
}
+1

ol 'fashioned factory.

class MyAnotherClass {
    MyClassFactory myClassFactory;

    @Inject
    MyAnotherClass( MyClassFactory myClassFactory ) {
        this.myClassFactory = myClassFactory;
    }

    public void someFunction() {
        String key = "1"; // read from DB
        myClass = myClassFactory.getMyClass( key );
    }
}

class MyClassFactory {
    public MyClass getMyClass( String key ) {
        Session session = new Session( key );
        MyClass myClass = new MyClass();
        myClass.setSession( session );
        return myClass;
    }
}
0

, , , . , , , , , , :

  • MyClass MyServiceAPI NOT Session. MyServiceAPI .

  • Sessionmust have its own sessionId(or any other) entered into its constructor. You can bind its value to Guice, to get something like: @Inject @SessionId public Session(String sessionId). Or you could insert sessionIdand SessionServicein Sessionso that it can get its own data from the service.

  • MyServiceAPImust contain Session.

0
source

All Articles