TNG / ArchUnit

A Java architecture test library, to specify and assert architecture rules in plain Java
http://archunit.org
Apache License 2.0
3.18k stars 288 forks source link

Find if a declared variable is a spring bean or not #1119

Open arundotin opened 1 year ago

arundotin commented 1 year ago

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 ??

rweisleder commented 1 year ago

Related thread on Stack Overflow with a possible answer

codecholeric commented 10 months ago

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.