简体   繁体   中英

Print non-managed Spring bean name

I have created one simple SpringBoot Application. There are two classes :

1) ManagedBean class

@Component
class ManagedBean
{
    public void fn()
    {
        System.out.println("B doin nothing");
    }
}

2) NonmangedBean : It has dependency of ManagedBean class

class NonmangedBean
{
    @Autowired
    ManagedBean mb;

    public void fn()
    {
        mb.fn();
        System.out.println("doin nothing");
    }
}

There is third Service class which has Rest End points.

@RestController
@RequestMapping("/")
class Service
{
    @Autowired 
    AutowireCapableBeanFactory beanFactory;

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("/getBeanNames")
    public List<String> printBeans() 
    {
        return Arrays.asList(applicationContext.getBeanDefinitionNames());
    }

    @GetMapping("/processBean")
    public String processBean()
    {
        NonmangedBean nb = new NonmangedBean();
        beanFactory.autowireBean(nb);
        nb.fn();

        return "Success";
    }
}

First I am calling /processBean endpoint which will crete Object of NonmangedBean class and autowires it. (Here my understading it that bean will live in Spring Container till i shutdown the server.)

After that I hit /getBeanNames endpoint to get all the bean names in Spring Container but I didn't find NonmangedBean in the list. I find ManagedBean in that list.

Questions :

1) Will this type of(NonmangedBean) autowired beans be stored in Spring Container? 2) Will this type of autowired beans die as soon as request process completed? 3) Am I doing anything wrong in printBeans method? Should I use anything else than applicationContext to get SpringBean lists? Open for your suggetions. Thanks in advance.

Here my understading it that bean will live in Spring Container till i shutdown the server

Your understanding is wrong it will die with the request ie the scope of the object is within that method( processBean ) only. The container will NOT manage your bean. Apart from that, there is no sense in using

@Autowired in your non managed bean. Since container doenn't manage it it will be null (unless you inject it using beanFactory.autowireBean(); ) and therefore answer to your question that if you can print any such bean using spring services is NO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM