ArchUnit
ArchUnit copied to clipboard
Find if a declared variable is a spring bean or not
I have to place this special architecture-rule in my project where classes that are annotated with @RestController
or @Service
or @Component
should include instance variables that are only Spring beans.
For example Let's take this class
@Service
public class HotelsService {
private Map<String, String> availableAreasHotelMap;
@Autowired
private HotelsDao hotelsDao;
public List<Hotel> fetchAllHotels() {
return dummyHotelsList();
}
}
The above should make my arch-unit test fail, because I haven't declared any bean for availableAreasHotelMap
.
Whereas if i include a bean this way
@Configuration
public class MyConfig {
@Bean("availableAreasHotelMap")
public Map<String, String> availableAreasHotelMap () {
return Map.of("india","hote-1","chicago","hotel-2");
}
}
my arch-unit test case should pass, after detecting a bean declaration. Not sure how to do this in arch-unit. Even for spring, it would be able to detect only during run-time, but how to do this during compile-time ?? is this impossible at all ??
Related thread on Stack Overflow with a possible answer
Just for completeness, you could go through your imported classes and e.g. collect the @Bean
annotated members with their type and name (from the @Bean
annotation), but in the end you would likely end up re-implementing Spring Bean resolution 😉 So probably it is easier as mentioned to just commit to a certain subset of ways to inject Spring Beans and enforce that instead.