是否可以将@Autowired
添加到类中,还可以向不使用这些自动装配类的类添加构造函数?
示例:
public class MyJob {
@Autowired
private MyService1 serv1;
@Autowired
private MyService2 serv2;
public MyJob(String filename) {
this.filename = filename;
}
}
在这里,我想将MyService1
和MyService2
视为理所当然,并使用构造函数初始化这些类@Bean
:
@Bean
public getMyJob1() {
return new MyJob("test1");
}
@Bean
public getMyJob2() {
return new MyJob("test2");
}
这可能吗?
答案 0 :(得分:2)
我认为最好的方法是为MyJob的实例创建一个工厂:
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);
}
}
答案 1 :(得分:0)
我只是使用filename
属性的setter:
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
}
然后,在工厂类中:
@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;
}