Pankaj Singhal
Pankaj Singhal

Reputation: 16043

Spring: Choosing constructor while Autowiring a Component

I've a Component as follows:

@Component
class A(){
    private s;
    public A(){}
    public A(String s){this.s=s;}
}

Here is the other class Where I'm auto wiring the above class:

@Component
class B(){

    @Autowire
    private A a;
}

In the above autowiring, I need to use the parameterized constructor. How can I pass the constructor args?

Upvotes: 1

Views: 2821

Answers (3)

Paul
Paul

Reputation: 20061

You can't, at least not via @Autowired in B but there are other ways to do it:

Wire the parameter into A's constructor:

One constructor is annotated with @Autowired because:

As of Spring Framework 4.3, the @Autowired constructor is no longer necessary if the target bean only defines one constructor. If several constructors are available, at least one must be annotated to teach the container which one it has to use.

@Component
class A(){
    private s;
    public A(){}

    @Autowired
    public A(@Value("${myval}") String s){this.s=s;}
}

Expose A as a @Bean

Straight from the docs:

@Configuration
public class AppConfig {
    @Bean
    public A a(@Value("${myval}") String s) {
        return new A(s);
    }
}

Construct A in B using an initialization callback

Docs

@Component
class B(){
    private A a;
    @Value("${myval}")
    private String myval;

    @PostConstruct
    private void init()
    {
        a = new A(myval);
    }
}

Upvotes: 2

hellojava
hellojava

Reputation: 5064

There is a concept of prototype bean which I think you require in your case. @Component will create a singleton bean and changing it in one place will change in all parent classes where this was injected.

You need to understand how to inject a prototype bean in singleton bean. Follow this example https://stackoverflow.com/a/25165971/949912

Upvotes: 0

Arthur Kushner
Arthur Kushner

Reputation: 99

Just use setters instead of constructor. If you want to create object by yourself with new keyword then this object will not be managed by container.

Upvotes: -1

Related Questions