Afterpropertiesset method and Init-method configuration description in spring

Source: Internet
Author: User
Tags getmessage

---restore content starts---

Today, we read the code written by predecessors using the Afterpropertiesset () method, and then nicely sorted out the spring bean load

1. Initializingbean.afterpropertiesset ()

The Initializingbean interface class in spring provides a way for the bean to define the initialization method, which contains only one method: Afterpropertiesset ().
The bean implements this interface and writes the initialization code in Afterpropertiesset ():

1  Public classAlarmqueue<t>ImplementsInitializingbean, Disposablebean, Component {2     Private Static FinalCLogger logger = Utils.getlogger (alarmqueue.class);3 4 @Autowired5 Threadfacade THF;6 @Autowired7     PrivateCloudbus bus;8 9     Privateredistemplate redistemplate;Ten     PrivateString key; One     PrivateRedisconnectionfactory Factory; A     Privateredisconnection Connection; -     PrivateLock lock =NewReentrantlock ();//based on underlying IO blocking considerations -     PrivateThread Alarmthread; the     Private BooleanIsinit =true; -     Private BooleanisClosed; -  -      Public voidsetredistemplate (redistemplate redistemplate) { +          This. redistemplate =redistemplate; -     } +  A      Public voidSetkey (String key) { at          This. Key =key; -     } -  - @Override -      Public void Afterpropertiesset()throwsException {// -Logger.info ("============== afterpropertiesset ================="); inFactory =redistemplate.getconnectionfactory (); -Connection =redisconnectionutils.getconnection (factory); toAlarmthread =NewAlarmthread (); +Alarmthread.setdaemon (true); - Alarmthread.start (); the     } *  $     classAlarmthreadextendsThread {Panax Notoginseng @Override -          Public voidrun () { the             Try { +                 if(isinit) { AThread.Sleep (30000); theIsinit =false; +                 } -  $Logger.info ("============== alarmthread Start ================="); $                  while(true) { -T value = Takefromtail (0); -                     if(Value! =NULL) { the                         Try { -                             //listener.onmessage (value);WuyiHandlealarmmsg amsg =Newhandlealarmmsg (); the Amsg.setalarmvalue (value.tostring ()); - Bus.maketargetserviceidbyresourceuuid (amsg, Alarmconstant.service_id_alarm_log, PLATFORM.G Etuuid ()); Wu bus.send (amsg); -}Catch(Exception e) { AboutLogger.error (String.Format ("fail to handle alarm! Alarm content:%s, Error:%s ", Value.tostring (), E.getmessage ())); $                         } -                     } -                 } -}Catch(interruptedexception e) { A                 Throw NewRuntimeException (String.Format ("Alarm thread interruptedexception! Error:%s ", E.getmessage ())); +             } the         } -     } $  the      PublicT Takefromtail (intTimeoutthrowsinterruptedexception { the lock.lockinterruptibly (); the         Try { thelist<byte[]> results =Connection.brpop (timeout, key.getbytes ()); -             if(Collectionutils.isempty (results)) { in                 return NULL; the             } the             return(T) Redistemplate.getvalueserializer (). Deserialize (Results.get (1)); About}Catch(Exception e) { the             Throw NewRuntimeException (String.Format ("fail to take the value from queue%s! Error: ", This. Key, E.getmessage ())); the}finally { the Lock.unlock (); +         } -     } the Bayi @Override the      Public voidDestroy ()throwsException { the         if(isClosed) { -             return; -         } the shutdown (); the redisconnectionutils.releaseconnection (connection, factory); theisClosed =true; the     } -  the     Private voidshutdown () { the alarmthread.interrupted (); the     }94  the @Override the      Public Booleanstart () { the         return true;98     } About  - @Override101      Public BooleanStop () {102         return true;103     }104}

It is not necessary to have a special configuration for the bean in the XML configuration file, and spring checks that the bean implements the Initializingbean interface after the configuration file has completed all of the bean's assignments. Call the Bean's Afterpropertiesset method if implemented.

2. Init-method Configuration

Although spring can call this bean customization method by Initializingbean completion of a bean initialization, this approach requires the bean to implement the Initializingbean interface. Once the bean implements the Initializingbean interface, the bean's code is coupled with spring. You can use the Init-method functionality provided by spring to perform a bean-custom initialization method.
In the following code, the class Monitorkafka does not implement any spring interfaces, and defines a method monitorkafkamsg () without parameters.

1  Public classAlarmlogmanagerimplextendsAbstractserviceImplementsApimessageinterceptor {2 3     Private Static FinalCLogger logger = Utils.getlogger (Alarmlogmanagerimpl.class);4 @Autowired5     PrivateCloudbus bus;6 @Autowired7     PrivateDatabasefacade dbf;8 @Autowired9     PrivateThreadfacade THF;Ten @Autowired One     PrivateRestfacade restf; A @Autowired -     PrivateSMSService SMSService; - @Autowired the     PrivateMailservice Mailservice; -  -   ....   -}
<bean id= "alarmlogmanagerclass
</bean>

Note: Destroy-method is the specified method called before the Bean is destroyed.
The Monitorkafkamsg () method in the Init-method configuration will be called after the bean initialization is completed, and spring requires that the Init-method be a parameterless method, or an exception will be thrown, and spring will abort the bean's subsequent processing. and throws a Org.springframework.beans.factory.BeanCreationException exception.

Summarize:
1. Initializingbean and Init-method can be used together, and spring will process the Initializingbean before processing Init-method. Init-method is performed through reflection, and Afterpropertiesset is executed directly, so afterpropertiesset is more efficient than Init-method, However, Init-method eliminates the bean dependency on spring and recommends the use of Init-method.
2. If a bean is defined as non-singleton, then Afterpropertiesset and Init-method are executed when each instance of the bean is created. The Afterpropertiesset and Init-method of a singleton bean are only called once when the Bean is first instantiated by an instance. In general, Afterpropertiesset and Init-method are applied on a single bean.
3. @PostConstruct and @predestory can implement similar functions by annotating them on a class-method basis.

Afterpropertiesset method and Init-method configuration description in spring

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.