Reputation: 143
I have a project structure similar to the one linked here: 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. However, my Service class itself uses Constructor Injection. 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. I'm not sure of how to create a Configuration class.
@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. 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?
Upvotes: 0
Views: 177
Reputation:
In your main module
@Configuration
@Import(PersistenceConfig.class)
public class ServiceConfig() {
}
In your utils module
@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.
Upvotes: 2