0

I have constructors that need dynamic values at rum time and was wondering if it
still can use dependency injection.Please let me know how can i do dependency injection using spring in this case.

public class User { 

    private String username;
    private int userid;

    User(String username, int userid) {
        this.username = username;
        this.userid = userid;
    }

    public String toString() {
        return "username" + userid;
    }
}

public class Superuser {

    private User user;

    public daomethod() {
        //some data access code that gets the username and id ......
        // now i need to pass this username and user id to the User constructor        
        user.toString();**     
    }
}
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120

2 Answers2

0

Use @javax.inject.Inject like this:

    @Inject
    User(String username, int userid) {
        this.username = username;
        this.userid = userid;
    }
DiogoSantana
  • 2,404
  • 2
  • 19
  • 24
0

If this is still an issue for people, Spring has aliases with which you can name registrations: http://springframework.net/doc/sdk/2.0/html/Spring.Core~Spring.Context.Support.TypeRegistry~RegisterType%28String,String%29.html

Then if you use an Abstract Factory in conjunction with these named registrations and a naming convention you can resolve these Depedency Injections in a very clean manner. I've written a simple .NET + Unity example (the basics are the same): https://dannyvanderkraan.wordpress.com/2015/06/29/real-world-example-of-dependency-injection-based-on-run-time-values/

Perhaps it helps people.

Danny van der Kraan
  • 5,344
  • 6
  • 31
  • 41