Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Spring constructor injection with multiple parameters

Suppose we have a Class A, and B. inside B's constructor, not only A is needed, but also some other String / boolean values. e.g

@Componenet(value = "B")
@DependsOn(value = "A")
public class B{
    ...
}
public B(A a_instance, String name1, String name2, boolean b1){
    ...
}

I know using annotation. but not knowing exactly, what should be done with those String/boolean values?

like image 392
Jeffrey.W.Dong Avatar asked Sep 15 '25 07:09

Jeffrey.W.Dong


1 Answers

Your question isn't entirely clear. Your B constructor appears to be outside of class B. Aside from that, assuming there are no other constructors, what you have won't work because Spring will look for a default constructor. I think what you're asking is what to do if you want to @Autowired that constructor to get String and boolean values in it. If so, you want something like this:

@Component
public class B {
    @Autowired
    public B(A a,
             @Value("${some.property.1}") String name1,
             @Value("${some.property.2}") String name2,
             @Value("${some.property.3}") boolean b1) {
        ...
    }
}

In this situation, @Value acts somewhat like @Qualifier would if you had multiple beans of type A.

like image 183
Ryan Stewart Avatar answered Sep 17 '25 22:09

Ryan Stewart