为了账号安全,请及时绑定邮箱和手机立即绑定

Spring:带有@Autowired(required = false) 参数的构造函数的

Spring:带有@Autowired(required = false) 参数的构造函数的

慕尼黑的夜晚无繁华 2021-07-03 18:09:29
我有一个服务类,我想用构造函数参数的不同传入值动态初始化它:@Servicepublic 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使用自己提供的@Autowired(required = false)参数(在本例中为自己的 url 和密码)在另一个 spring 组件类中对其进行初始化?这段代码会是什么样子?
查看完整描述

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

   } 

}


查看完整回答
反对 回复 2021-07-14
?
收到一只叮咚

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;

    }


查看完整回答
反对 回复 2021-07-14
  • 2 回答
  • 0 关注
  • 472 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信