2 回答
TA贡献1906条经验 获得超10个赞
你可以这样做
@Configuration
class SomeConfigClass {
@Autowired
SomeProperties someProperties
@Value("${url1}")
String url1
@Value("${password1}")
String password1
..............
// Do this for other url's and properties or check out @ConfigurationProperties
..............
@Bean("someService1")
public SomeService() {
return new SomeService(someProperties, url1, password1);
}
@Bean("someService2")
public SomeService() {
return new SomeService(someProperties, url2, password2);
}
...............
..............
}
创建工厂类
@Configuration //typo corrected
class SomeServiceFactory {
@Autowired // Spring will Autowire all instances of SomeService with bean name as key
Map<String, SomeService> someServiceMap;
public SomeService getSomeServiceByName(String name) {
return someServiceMap.get(name);
}
}
然后你可以像这样使用实例
@RestController
class SomeController {
@Autowired
SomeServiceFactory someServiceFactory;
public void someEndpoint() {
SomeService someService1 = SomeServiceFactory.getSomeServiceByName("someService1"); //You need to decide what argument to pass based on condition
someService1.someFunction(...); // this will have url1 and password1
}
}
TA贡献1821条经验 获得超4个赞
用户名和密码从何而来?也许您可以简单地从构造函数中删除它们并使用 @Value 注释从属性文件中读取值?
@Service
public class SomeServiceImpl implements SomeService {
private final SomeProperties someProperties;
@Value("${service.url}")
private String url;
@Value("${service.password}")
private String password;
private final Logger log = LoggerFactory.getLogger(SomeServiceImpl.class);
@Autowired
public SomeServiceImpl(SomeProperties someProperties) {
this.someProperties = someProperties;
}
添加回答
举报