How to autowire an object in spring in an object created with new

前端 未结 5 2072
广开言路
广开言路 2021-02-07 12:35

all I want to do is autowire the field backgroundGray in the NotesPanel class, but all I get is the exception below.

So, question is, how to autowire it correctly ? It r

5条回答
  •  遇见更好的自我
    2021-02-07 13:03

    You can perform DI on any instance, whether Spring managed or created with new.

    To do so, use the following code...

    AutowireCapableBeanFactory awcbf = applicationContext.getAutowireCapableBeanFactory();
    awcbf.autowireBean(yourInstanceCreatedWithNew);
    

    This is also a great way to introduce Spring into an application that was developed originally without Spring - as it allows you to use Spring where you want it without having to convert every class in the application into a Spring bean (because typically, you can't use a Spring bean without a Spring bean).

提交回复
热议问题