Step 1 of Spring principles-explore SpringIoc principles based on excel imports

Source: Internet
Author: User

Step 1 of Spring principles-explore SpringIoc principles based on excel imports
Problem description

An excel worksheet contains two sheet pages. The first sheet stores the data of the current month, and the second sheet stores the data of the next month, the data in the two sheet pages correspond to two different tables in the database respectively. How can we import data from excel to the database.

Problem Analysis 1 excel data parsing: Use POI or JXL2 data ing because two sheet pages correspond to two different tables respectively, it involves the question of the number of picks. Three data storage needs to be processed separately: using hibernate to save objects can solve the problem of analysis. We can easily think of a solution to this month's sheet page: parse data-> data ing-> save data the next month's sheet page: parse data> data ing> save data on multiple sheet pages. What should I do? Continue to work like this? My solution can be parsed separately or saved separately. The only difference is data ing. Based on this: we first construct the data parsing method:
/*** Read the excel file to Map * the key is the sheet Page name, and the value is the two-dimensional data parsed from the exceld cell * @ param file * @ return */private static Map
 
  
Reader (File file) {Map
  
   
Map = new HashMap
   
    
(); // Cyclically parse map. put ("excelService4CurrentMonth", null) based on the sheet Page name; map. put ("excelService4CNextMonth", null); return map ;}
   
  
 

Save method: Create a saved service.
Package com. springIoc. service; import com. springIoc. mapper. IExcelMapper;/***** excel service class * @ author Administrator **/public class ExcelServer {/** excel encapsulation class for decoupling and use */private IExcelMapper excelMapper; /** two-dimensional array returned by excel */private String [] [] values; public String [] [] getValues () {return values ;} public void setValues (String [] [] values) {this. values = values;} public IExcelMapper getExcelMapper () {return excelMapper;} public void setExcelMapper (IExcelMapper excelMapper) {this. excelMapper = excelMapper;}/** you can use the hibernate save method to save the array */public void save (String [] [] values) {Object obj = excelMapper. mappering (values); System. out. println (obj + "saved successfully ");}}

We can see that the above Code has an interface called IExcelMapper. Its function is to convert the data in the two-dimensional array to the object that can be saved by hibernate. The specific solution depends on its implementation class. This month returns the encapsulated objects of this month, and the next month returns the encapsulated objects of the next month.
Package com. springIoc. mapper;/*** excel ing interface * @ author Administrator **/public interface IExcelMapper {public abstract Object mappering (String [] [] values );}

This implementation class is used for data ing.
Package com. springIoc. mapper. impl; import com. springIoc. mapper. IExcelMapper;/*** Data encapsulation for this month * @ author yj. shi **/public class ExcelMapper4CurrentMonth implements IExcelMapper {@ Overridepublic Object mappering (String [] [] values) {System. out. println ("Data encapsulation for this month"); return "data for this month ";}}
Does calling interfaces in the service enable data decoupling? Whether the service and data ing Class (ExcelMapper4CurrentMonth) can be opened at will.
The implementation is decoupled, and the next step is the corresponding relationship. How do I know which of the servcie's ExcelMapper is? Maybe we can write the corresponding logic by ourselves. However, I think the feasible solution is to use the Ioc idea of Spring. Control flip: not the mapper that my service is looking for, but the mapper that I am looking. You are not looking for me, but for you, so that you do not need to write that complex correspondence. From looking for you to looking for you, you are not much easier. Dependency injection: What is injected? Is the injection of reference objects. IExcelMapper is a reference declaration. How can I inject the object to be referenced? It's easy to write a properites file to illustrate their corresponding relationship.
# Excel ing excelMapper4CurrentMonth = com. springIoc. mapper. impl. excelMapper4CurrentMonth # excel ing in the next month excelMapper4NextMonth = com. springIoc. mapper. impl. excelMapper4NextMonthexcelService4CurrentMonth = com. springIoc. service. excelServerexcelService4CNextMonth = com. springIoc. service. excelServerexcelService4CurrentMonth. excelMapper = excelMapper4CurrentMonthexcelService4CNextMonth. excelMapper = excelMapper4NextMonth

There is a corresponding relationship. The next step is how to handle it. Spring is a container. The creation of objects and the establishment of dependency are best handled by the sring container. Write a spring container. Just write the ing Class according to the properites above.
Package com. springIoc. container; import java. io. IOException; import java. io. inputStream; import java. lang. reflect. invocationTargetException; import java. util. hashMap; import java. util. map; import java. util. properties; import org. apache. commons. beanutils. propertyUtils;/*** is equivalent to the spring container used to save bean * @ author yj. shi **/public class Container {private static Map
 
  
Map = new HashMap
  
   
(); Public Container () {Properties properties = new Properties (); InputStream in = null; try {in = Container. class. getClassLoader (). getResourceAsStream ("ioc. properties "); properties. load (in); for (Map. entry
   
    
Entity: properties. entrySet () {String key = entity. getKey (). toString (); String value = entity. getValue (). toString (); mappeingBean (key, value) ;}} catch (Exception e) {e. printStackTrace ();} finally {if (in! = Null) {try {in. close ();} catch (IOException e) {e. printStackTrace ();}}}} /*** ing the properties content * @ param key * @ param value * @ throws ClassNotFoundException * @ throws parameters * @ throws InstantiationException * @ throws NoSuchMethodException * @ throws InvocationTargetException */ private void mappeingBean (String key, string value) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {String [] parts = key. split ("\\. "); if (parts. length = 1) {// create a map object. put (parts [0], Class. forName (value ). newInstance ();} else {// inject reference relationship Object target = getBeanById (parts [0]); Object resource = getBeanById (value); PropertyUtils. setProperty (target, parts [1], resource );}} /*** use the key to get data from the spring container * @ param key * @ return */public static Object getBeanById (String key) {return map. get (key );}}
   
  
 


Now, let's write the test method.
Package com. springIoc. test; import java. io. file; import java. util. hashMap; import java. util. map; import com. springIoc. container. container; import com. springIoc. service. excelServer; public class TestMain {@ SuppressWarnings ("static-access") public static void main (String [] args) {Container container = new Container (); Map
 
  
Map = reader (null); for (String key: map. keySet () {ExcelServer service = (ExcelServer) container. getBeanById (key); service. save (map. get (key) ;}}/*** read excel into Map * key as the sheet Page name, value is the two-dimensional data parsed from the exceld cell * @ param file * @ return */private static Map
  
   
Reader (File file) {Map
   
    
Map = new HashMap
    
     
(); // Cyclically parse map. put ("excelService4CurrentMonth", null) based on the sheet Page name; map. put ("excelService4CNextMonth", null); return map ;}}
    
   
  
 

Conclusion: springIoc controls the flip of a role, from active searching to waiting for someone to look for me. After finding out what I am doing, I am doing dependency injection and giving me the object I want through setter, constructor, or interface. In this way, the decoupling between classes is realized, and the reference relationship between dependent objects is established. It's easy and enjoyable. The specific implementation should be done by the spring container. Code Link

Related Article

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.