The design principle of spring is to use as many instances as possible and as many single-State instances as possible, which can be seen from its bean configuration file. However, sometimes injection is not the best solution, especially for the processing of legacy classes. Static classes may be a better solution, because static classes do not need to be injected, there is no need to change the original code too much. One problem with spring injection is that normal classes cannot obtain bean instances in bean files. This means that webapplicationcontextutils can be used in the Web Servlet environment. If it is a common class, it will not be easy to handle. This requires some design skills. The following is an example of a static Class Using Bean files.
Public class userinfoutil
{
Private iuserinfo userinfo;
Private Static userinfoutil Info;
Public void setuserinfo (iuserinfo userinfo)
{
This. userinfo = userinfo;
}
Public void Init ()
{
Info = this;
Info. userinfo = This. userinfo;
}
Public static int adduserlogincnt (string phonenumber)
{
Return info. userinfo. adduserlogincnt (phonenumber );
}
}
Bean file configuration
<Bean id = "userinfoutil" class = "com. Huawei. Aimi. webportal. Service. userinfoutil" init-method = "init">
<Property name = "userinfo" ref = "userinfo"/>
</Bean>
In this way, you can use a static stove to access the spring Singleton configuration.
2. Injection Using Annotations:
Public class userinfoutil
{
@ Autowired
Private iuserinfo userinfo;
Private Static userinfoutil Info;
Public void setuserinfo (iuserinfo userinfo)
{
This. userinfo = userinfo;
}
@ Postconstruct
Public void Init ()
{
Info = this;
Info. userinfo = This. userinfo;
}
PublicStaticInt adduserlogincnt (string phonenumber)
{
Return info. userinfo. adduserlogincnt (phonenumber );
}
}
Notes
1. Be sure to use the initialization method. If there is no init method, it will be directly in the constructor. If new () is used, a problem will occur.
2. This must be used only in the init method and not in the constructor.
3. Do not implement spring-related interfaces, but use initialization methods.