Issue
I want to write a kind of integration test, but only for a specific class. Which means I want all fields in that class to be automatically wired, but neglect any classes inside the same directory.
Example:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestConfig.class})
public class JunitTest {
@Autowired
private MyService service;
}
//how to only scan that specific class?
@ComponentScan(basePackageClasses = {MyService.class, MyInjectedService.class})
@Configuration
public class TestConfig {
}
@Service
public class MyService {
@Autowired
private MyInjectedService service;
}
Here I want spring to neglect any classes in the same directories as the both basePackageClasses
mentioned.
Solution
You could make use of filters to customize scanning. There you can extend the ComponentScan Annotation with Attributes like this:
@ComponentScan(
basePackages = {"com.my.package"},
useDefaultFilters = false,
includeFilters = {
@Filter(type = FilterType.ASSIGNABLE_TYPE, value = {MyService.class, MyInjectedService.class})
})
Answered By - sven.kwiotek
Answer Checked By - David Marino (JavaFixing Volunteer)