我有一个服务类,我想使用构造函数参数的不同传入值来动态初始化:
@Service
public class SomeServiceImpl implements SomeService {
private final SomeProperties someProperties;
private final String url;
private final String password;
private final Logger log = LoggerFactory.getLogger(SomeServiceImpl.class);
@Autowired
public SomeServiceImpl(SomeProperties someProperties,
@Autowired(required = false) String url,
@Autowired(required = false) String password) {
this.someProperties = someProperties;
this.url = url;
this.password = password;
}
是否可以在运行时通过使用自己提供的@Service
参数(在本例中为自己的url和密码)在另一个spring组件类中初始化此@Autowired(required = false)
?这段代码看起来如何?
答案 0 :(得分:1)
您可以这样做
@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);
}
...............
..............
}
创建工厂类
@Comfiguration
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
}
}
答案 1 :(得分:0)
用户名和密码来自哪里? 也许您可以简单地将它们从构造函数中删除,并使用@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;
}