简体   繁体   English

@Autowire带有构造函数args的Spring Bean?

[英]@Autowire Spring Bean with Injected Constructor args?

I have a project structure similar to the one linked here: https://stackoverflow.com/a/29583882/1243462 . 我的项目结构类似于此处链接的项目结构: https : //stackoverflow.com/a/29583882/1243462 I have a util library containing a Service class in one JAR, meant to be consumed from another Java library/Maven project. 我有一个包含在一个JAR服务类,打算从另一个Java库/ Maven项目消耗一个实用程序库 However, my Service class itself uses Constructor Injection. 但是,我的Service类本身使用构造函数注入。 So, where the original question had: 因此,原始问题在哪里:

@Service
public class PermissionsService { ... }

I have 我有

@Service
public class PermissionsService {

  public PermissionsService(@Autowired PermissionsDao dao) { 
   //assign private dao field to autowired dao
  }

}

And, like the original post, I want to create an instance of PermissionsService and inject it into my client/consumer application. 并且,就像原始帖子一样,我想创建一个PermissionsService实例,并将其注入到我的客户端/消费者应用程序中。 I'm not sure of how to create a Configuration class. 我不确定如何创建Configuration类。

 @Configuration
 public class PersistenceConfig {

   public PermissionsService getPermissionsServiceBean() {
     //What goes here?
   }
}

For now, I have a workaround where I replaced the @Autowired PermissionsDao constructor argument with a field injection, and having a no-args constructor. 现在,我有一种解决方法,其中我将@Autowired PermissionsDao构造函数参数替换为字段注入,并使用了无参数的构造函数。 This allows me to: 这使我能够:

 @Configuration
 public class PersistenceConfig {

   public PermissionsService getPermissionsServiceBean() {
     return new PermissionsService();
   }
}

But, since Field injection is discouraged, what is the right way to structure this code? 但是,由于不鼓励使用字段注入,因此构造此代码的正确方法是什么?

In your main module 在您的主模块中

@Configuration
@Import(PersistenceConfig.class)
public class ServiceConfig() {

}

In your utils module 在您的utils模块中

@Configuration
@ComponentScan(basePackages = {"path-to-persistence-service-and-any-dependencies"})
public class PersistenceConfig {

}

The fact that you use constructor injection for PermissionsDao should not matter if you get the configuration right. 您使用构造器注入的事实PermissionsDao如果你得到正确的配置应该没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM