jabrena / spring-boot-user-beans

A visual way to increase the developer awareness to minimize the number of Beans in memory.
https://jabrena.github.io/spring-boot-user-beans/
Apache License 2.0
52 stars 3 forks source link

Find a way to get class from dependencies #148

Open jabrena opened 1 year ago

jabrena commented 1 year ago

Found a way:

package io.github.jabrena.userbeans;

import static org.assertj.core.api.Assertions.assertThat;

import io.github.jabrena.support.SupportController;
import io.github.jabrena.support.TestApplication;
import java.util.Comparator;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest(
    classes = { TestApplication.class },
    properties = { "management.endpoints.web.exposure.include=beans,userbeans" }
)
class UserBeansServiceTests {

    @Autowired
    private UserBeansService userBeansService;

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    void shouldRetrieveAllBeans() {
        //Given
        var beanCounter = 0;

        record BeanDocument(String beanName, String beanPackage) {}

        //When
        var beanList = userBeansService
                .getBeansDocuments()
                .stream()
                .filter(bd -> bd.dependencies().size() > 0)
                .flatMap(bd -> bd.dependencies().stream())
                .distinct()
                .map(str -> {
                    try {
                        Class<?> myClass = applicationContext.getBean(str).getClass();
                        String beanName = (myClass.getSimpleName().length() == 0) ? myClass.getName() : myClass.getSimpleName();
                        String beanPackage = myClass.getPackageName();
                        return new BeanDocument(beanName, beanPackage);
                    } catch (NoSuchBeanDefinitionException e) {
                        //Empty on purpose
                    }
                    return new BeanDocument(str, "UNKNOWN");
                })
                .sorted(Comparator.comparing(BeanDocument::beanName))
                .peek(System.out::println)
                .toList();

        //Then
        assertThat(beanList).hasSizeGreaterThan(beanCounter);
    }
}
jabrena commented 1 year ago