我的项目结构类似于此处链接的项目结构:https://stackoverflow.com/a/29583882/1243462。我有一个 util库,该库在一个JAR中包含一个Service类,该类将从另一个Java库/ Maven项目中使用。但是,我的Service类本身使用构造函数注入。因此,原始问题在哪里:
@Service
public class PermissionsService { ... }
我有
@Service
public class PermissionsService {
public PermissionsService(@Autowired PermissionsDao dao) {
//assign private dao field to autowired dao
}
}
而且,就像原始帖子一样,我想创建一个PermissionsService
的实例并将其注入到我的客户/消费者应用程序中。我不确定如何创建Configuration类。
@Configuration
public class PersistenceConfig {
public PermissionsService getPermissionsServiceBean() {
//What goes here?
}
}
目前,我有一种解决方法,其中我将@Autowired PermissionsDao
构造函数参数替换为字段注入,并使用了无参数的构造函数。这使我能够:
@Configuration
public class PersistenceConfig {
public PermissionsService getPermissionsServiceBean() {
return new PermissionsService();
}
}
但是,由于不鼓励使用字段注入,因此构造此代码的正确方法是什么?
答案 0 :(得分:2)
在您的主模块中
describe(`interceptor: yourinterceptor`, () => { // CHANGE HERE
let httpMock: HttpTestingController;
let injector: TestBed;
function createTestModule(providers: Provider[] = []) {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: YOUR_INTERCEPTOR, // CHANGE HERE
multi: true
},
...providers
]
});
injector = getTestBed();
httpMock = injector.get(HttpTestingController);
}
beforeEach(() => {
// empty
});
afterEach(() => {
httpMock.verify();
});
describe('request with headers', () => {
beforeEach(() => {
createTestModule();
});
it('should make the request with headers', inject([HttpClient], (http: HttpClient) => {
http.get('/dummy').subscribe();
const httpRequest: TestRequest = httpMock.expectOne('/dummy');
expect(httpRequest.request.headers.has("YOUR_HEADER")).toBeTruthy(); // CHANGE HERE
}));
});
});
在您的utils模块中
@Configuration
@Import(PersistenceConfig.class)
public class ServiceConfig() {
}
如果正确配置,则对@Configuration
@ComponentScan(basePackages = {"path-to-persistence-service-and-any-dependencies"})
public class PersistenceConfig {
}
使用构造函数注入这一事实应该无关紧要。