How to inject a spring bean into a static method or non-spring bean

Source: Internet
Author: User

Sometimes you need to get a spring bean object on your own as needed in your new object, or in some Util method or property, to do some work, but because your new object and Util method are not managed by spring, if you use it directly on the property that you depend on @Autowiredyou will be able to report an error that cannot be injected, or it will not be reported, but a null pointer exception is quoted when used. All in all, it cannot be injected because it is not managed by the IOC container.

Spring provides two interfaces: Beanfactoryaware and Applicationcontextaware, both of which inherit from the aware interface. The following are the declarations of these two interfaces:

publicinterfaceextends Aware {    voidsetBeanFactorythrows BeansException;}
publicinterfaceextends Aware {    voidsetApplicationContextthrows BeansException;}

As described in the spring official documentation, when the spring Bean is initialized, the interface method implemented by the bean is automatically invoked if a bean is detected to implement one of the two interfaces. As you can see, both of these methods pass the factory object of the IOC container management bean to the current bean, which means that if we save the factory object to a static property in the current bean, we can get the bean we need from the factory object. The following is a springbeanutil implemented using Applicationcontextaware:

 Public classSpringbeanutilImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext; Public void Setapplicationcontext(ApplicationContext ApplicationContext)throwsbeansexception {springbeanutil.ApplicationContext= ApplicationContext; } Public Static<T> TGetbean(Class<t> clazz) {return(T) ApplicationContext.Getbean(Clazz); } Public StaticObjectGetbean(String name)throwsbeansexception {returnApplicationContext.Getbean(name); }}

It is also necessary to specify in the configuration file an instance of the current class to be created:

<bean id="springBeanFactory" class="com.business.util.SpringBeanUtil"/>

As you can see, we have declared a static property of type ApplicationContext in Springbeanutil, and in Setapplicationcontext () The ApplicationContext method assigns the obtained value to the static property so that we can get the beans managed by the IOC container through ApplicationContext in the other two static methods of the declaration. Here is a sample test:

public   Classroom {public  void   () {Student Student = Springbeanutil. (Student.); System. out . println   (student); } public  static  void   () {Student Student = Springbeanutil. (Student.); System. out . println  ( "Is it not empty?"  + (null ! = student)); }}
publicclass Student {  @Override  publictoString() {    return"I am a student.";  }}
<bean id="springBeanFactory" class="com.util.SpringBeanUtil"/><bean id="student" class="com.domain.Student"/>

The following are the driver classes:

publicclass BeanApp {  publicstaticvoidmain(String[] args) {    newClassPathXmlApplicationContext("com/resources/application.xml");    ClassRoom.describeClassRoomCapacity();    newClassRoom();    classRoom.describeStudent();  }}

In the driver class, we first use Classpathxmlapplicationcontext to load the beans in the configuration file. As you can see, we have created a springbeanutil and a student bean. We first obtained the student instance in the static method and printed it out, and we also obtained the student instance through Springbeanutil in the new classroom instance, and output it. The output is as follows:

trueI am a student.

As you can see, both in the static method and in the instance of manual new, we have successfully acquired the beans managed by the IOC container. If we want to get Springbean in a static property, it's actually very simple, just assign a value to the property as follows:

privatestatic Student student = SpringBeanUtil.getBean(Student.class);

How to inject a spring bean into a static method or non-spring bean

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.