Scenario Description:
Sometimes we need to load some infrequently-changed data into the cache when the app starts, avoid querying the database or other data sources every time the request is made, to improve performance (preparing the connection, establishing the connection, closing the connection, Reduce the number of IO data read). If the spring frame is used in the application, it is possible to implement this function with spring mechanism.
Solution:
1: Write a class, implement the Beanpostprocessor interface, this interface has two methods.
(1): Postprocessbeforeinitialization method, call this method before bean initialization defined in spring
(2): Postprocessafterinitialization method, call this method after bean initialization defined in spring
Example code:
public class Cachebeanpostprocessor implements Beanpostprocessor {
@Override public
Object Postprocessafterinitialization (Object obj, String arg1) throws Beansexception {
try {
if (obj instanceof Columnservice) {
((columnservice) obj). Getcolumnlist ();//Load column data
}else if (obj instanceof Tradeserviceimpl) { (
(Tradeserviceimpl) obj). Gettradelist ();//Load Industry data
}
} catch (Exception e) {
e.printstacktrace ();
}
return obj;
}
@Override Public
Object Postprocessbeforeinitialization (Object arg0, String arg1)
throws Beansexception {
//TODO auto-generated method stub
return arg0;
}
}
2: In the spring XML file, add
<!--initial cache data, which is used before and after the bean defined in spring is initialized with this implementation class--
<bean id= "Cachebeanpostprocessor" class= "Com.guagua.cache.CacheBeanPostProcessor"/>
3: After loading the data, where the data exists, you will decide, I This example is placed in a "static variable"
@Service ("Columnservice") Public
class Columnserviceimpl implements Columnservice {public
static list< column> columnlist = new arraylist<column> ();
@Autowired
private Columndao Columndao;
public void Setcolumndao (Columndao columndao) {
This.columndao = Columndao;
}
@Override public
list<column> getcolumnlist () throws Exception {
columnlist = columndao.getcolumnlist () ;
return columnlist;
}
}
Concluding remarks:
If in doubt, please make an objection.