In the first few days, I got a test to initialize bean properties using the properties file. During the two days of work, I need to extract some configurations to the properties file, however, if one of the attributes is Map type and the method similar to Map Initialization is not found for a long time on the Internet, the system can continue to use the initialization Map method before finding the initialization Map method, the init method is temporarily used to manually initialize Map. As follows:
First, implement the InitializingBean interface for classes with Map attributes.
Code snippet:
[Java]
Public class SsoMailConfigImpl implements InitializingBean, SsoMailConfig
{
Private String userDomainMapInit; // format and save the Map to userDomainMapInit 0: mail.com.cn | 1: test.com.cn through properties.
Private Map <String, String> userDomainMap; // initialize userDomainMapInit data to Map using the afterPropertiesSet () method.
}
Then implement the afterPropertiesSet () method in InitializingBean.
Code:
[Java]
Public void afterPropertiesSet () throws Exception
{
UserDomainMap = new HashMap <String, String> ();
String [] userDomainArr = userDomainMapInit. split ("\\| ");
String [] tempKeyValue;
For (String userDomainEntry: userDomainArr)
{
TempKeyValue = userDomainEntry. split (":");
If (tempKeyValue. length = 2)
{
UserDomainMap. put (tempKeyValue [0]. trim (), tempKeyValue [1]. trim ());
}
}
}
By default, the Spring container uses the Singleton mode to create a Bean. Therefore, this initialization is only executed once. In this way, you can manually initialize the Map attribute.
Spring configuration file code snippet:
[Html]
<Bean id = "propertyFileForMailConfig"
Class = "org. springframework. beans. factory. config. PropertyPlaceholderConfigurer">
<Property name = "location">
<Value> ssomailconfig. properties </value>
</Property>
</Bean>
<Bean id = "emailConfig" class = "com. neusoft. education. dcp. apps. sso. SsoMailConfigImpl">
<Property name = "userDomainMapInit" value = '$ {USER_DOMAIN_MAP_INIT}'/>
</Bean>
I think there must be a more concise method to implement properties to initialize Map, hope to have this experience to my friends leave a message or Mail me, arvin.rong@gmail.com, thank you