java—如何在spring中在后期构造时自动连接此依赖关系

dy2hfwbg  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(236)

我有下面的代码在 @PostConstruct 在spring托管代码中的块。

class A {

    private BoogleFeature boogle;

    @PostConstruct
        public void createBoggleClient() {
                SDKPersona.SDKPersonaBuilder sdkBuilder =
                        new AppIdentifier.SDKPersonaBuilder()
                                .setRegistryId(config.getRegistryId())
                                .setRegistrySecret(config.getRegistrySecret())

                boggle = new BoggleFeature(sdkBuilder.build());
        }
    }
}

现在我不想再做了 boggle = new BoggleFeature(sdkBuilder.build()); 把它做成豆子,注射成脱附剂。我怎样才能做到这一点。

ycl3bljg

ycl3bljg1#

你可以用 GenericApplicationContext 动态注册bean @PostConstruct 这种方式:

@Component
public class BoogleFactory {

  @Autowired
  private GenericApplicationContext context;

  @PostConstruct
  public void createBoggleClient() {
    //build the sdk
    String sdk = "Boogle SDK";

    //then register the bean in spring context with constructor args
    context.registerBean(BoogleFeature.class,sdk);
  }

}

要动态注册的bean:

public class BoogleFeature {

  private String sdk;

  public BoogleFeature(String sdk) {
    this.sdk = sdk;
  }

  public String doBoogle() {
    return "Boogling with " + sdk;
  }
}

然后,您可以在应用程序中的任何位置使用:

@Component
class AClassUsingBoogleFeature {
   @Autowired
   BoogleFeature boogleFeature; //<-- this will have the sdk instantiated already
}

下面的测试证明,在spring上下文初始化之后,
(将初始化 BooglerFactory 然后打电话给 @Postcontruct 方法btw),
你可以用 Boogler@Autowired 任何地方。

@SpringBootTest
public class BooglerTest {

  @Autowired
  BoogleFeature boogleFeature;

  @Test
  void boogleFeature_ShouldBeInstantiated() {
    assert "Boogling with Boogle SDK".equals(boogleFeature.doBoogle());
  }

}
``` `registerBean` 有更强大的选择,看看这里。
utugiqy6

utugiqy62#

你试试下面,你可以把下面的代码放到come配置类中

@Bean(name="boggleFeature")
    public BoggleFeature createBoggleClient() {
        SDKPersona.SDKPersonaBuilder sdkBuilder =
            new AppIdentifier.SDKPersonaBuilder()
                .setRegistryId(config.getRegistryId())
                .setRegistrySecret(config.getRegistrySecret())

        return new BoggleFeature(sdkBuilder.build());
    }

然后你可以在任何地方使用autowired

@Autowired
    private BoogleFeature boogle

相关问题