最初,有一个service
实例用于访问数据库,现在我们要添加一个只读实例。因此,我在配置中添加了serviceReadonly
。
@Configuration
public class Config {
@Bean Service service() {...};
@Bean Service serviceReadonly() {...};
@Bean Proxy proxy() {return new Proxy(serviceReadonly())}; // replace the original Proxy(service())
}
但是service
也自动连接到Proxy
@Component
public class Proxy {
@Autowired
public Proxy(Service service) {this.service = service;}
}
我很困惑将哪个Service
注入我的API?服务还是serviceReadonly?
@Component
public class API {
@Autowired
public API(Proxy proxy) {this.proxy = proxy;}
}
Proxy
和API
类在另一个共享库中,因此最好避免对该库进行更改。同样,service
自动连接到其他组件。
简短回答:@Bean Service service()
说明:Spring文档here的摘录
按属性名称自动布线。春天找豆子一样名称为需要自动装配的属性。例如,如果bean定义被设置为按名称自动装配,并且包含一个主属性(即,它具有setMaster(..)方法),Spring会查找bean定义为master,并使用它来设置属性。
它将是@Bean Service service()
,因为Spring会找到与属性相同名称的bean,即,在正式Spring Service
中定义的guide。您可能还需要查看@Qualifier annotation。这是因为,如果容器中没有一个构造函数参数类型的bean,那么就会引发致命错误,如Spring文档here所述。在这种情况下,您可以使用@Qualifer批注指定所需的bean。