membersound
membersound

Reputation: 86935

How to autowire services outside of the constructor?

Is it possible to add @Autowired to a class, and also add a constructor to that class that does not use these autowired classes?

Example:

public class MyJob {
    @Autowired
    private MyService1 serv1;

    @Autowired
    private MyService2 serv2;

    public MyJob(String filename) {
        this.filename = filename;
    }
}

Here I want to take MyService1 and MyService2 for granted, and just initialize those class @Bean by using the constructor:

@Bean
public getMyJob1() {
    return new MyJob("test1");
}

@Bean
public getMyJob2() {
    return new MyJob("test2");
}

Is that possible?

Upvotes: 1

Views: 396

Answers (2)

Krzysztof Cichocki
Krzysztof Cichocki

Reputation: 6412

I think the best way is to make a Factory for the MyJob's instances:

public class MyJobFactory {
    private MyService1 serv1;    
    private MyService2 serv2;

    @Autowired
    public MyJobFactory(MyService1 serv1, MyService2 serv2) {
        this.serv1 = serv1;
        this.serv2 = serv2;
    }

    public MyJob myJob(String filename) {
        return new MyJob(filename, serv1, serv2);
    }
}

Upvotes: 2

fps
fps

Reputation: 34480

I'd simply use a setter for the filename property:

public class MyJob {
    @Autowired
    private MyService1 serv1;

    @Autowired
    private MyService2 serv2;

    private String filename;

    public void setFilename(String filename) {
        this.filename = filename;
    }

    // getter for filename
}

And then, in the factory class:

@Bean
public MyJob getMyJob1() {
    MyJob job = new MyJob();
    job.setFilename("test1");
    return job;
}

@Bean
public MyJob getMyJob2() {
    MyJob job = new MyJob();
    job.setFilename("test2");
    return job;
}

Upvotes: 0

Related Questions