The first step of spring principle--importing Excel into columns to explore SPRINGIOC principle

Source: Internet
Author: User

Problem Description

An Excel has two sheet page, the first sheet page holds this month's data, the second sheet page holds the data of the next month, the data in the two sheet pages correspond to the two different tables in the database respectively, how to implement the import of Excel to the database.

Problem Analysis1 Excel Data parsing:using POI or JXL2 Data mappingbecause the two sheet pages correspond to the different two tables, it involves the question of picking numbers, which is to be dealt with separately3 Data storage:You can save objects with HibernateSolution Solutionsbased on the analysis of analytical problems, it is easy to think of a solutionthis month sheet: Data map ---save data by parsing datanext month sheet page: Data map ---save data by parsing dataWhat if I have more than one sheet page? Continue to do the same? My planfirst, the resolution can be extracted separately, save can be extracted separately, the only increase is the data map. based on this: we first construct the method of data parsing:
/** * Read Excel into MAP *    key for sheet page name, value for the two-dimensional data that resolves the Exceld cell * @param file * @return */private static MAP<STRING,STR Ing[][]> Reader (file file) {map<string,string[][]> map=new hashmap<string,string[][]> ();// The sheet page name can be used to parse Map.put ("Excelservice4currentmonth", null), Map.put ("Excelservice4cnextmonth", null), and return map;

Save method: We will create a saved service.
Package Com.springioc.service;import com.springioc.mapper.iexcelmapper;/** * Excel service class * @author Administrator * */ public class ExcelServer {/**excel wrapper class, for decoupling using */private iexcelmapper Excelmapper;/**excel returned two-dimensional array */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;} /** can save the array by hibernate save */public Void Save (string[][] values) {Object obj=excelmapper.mappering (values); System.out.println (obj+ "Save Succeeded");}}

You can see that the above code has an interface called Iexcelmapper, and his role is to convert the data in a two-dimensional array into hibernate-saved objects.specifically how to deal with it depends on his implementation class. This month returns the wrapped object of the month, and returns the object that is encapsulated in the month after the second month.
Package com.springioc.mapper;/** * Excel Mapping Interface * @author Administrator * */public interface Iexcelmapper {public abstract Ob Ject mappering (string[][] values);}

What his implementation class does is data mapping.
Package Com.springioc.mapper.impl;import com.springioc.mapper.iexcelmapper;/** * This month data encapsulation * @author Yj.shi * */public Class Excelmapper4currentmonth implements iexcelmapper{@Overridepublic Object mappering (string[][] values) { SYSTEM.OUT.PRINTLN ("Data package of the Month"); return "Data of the Month";}}
Is it possible to decouple the data by invoking the interface in the service? Service and data mapping classes (Excelmapper4currentmonth) are not ready to be opened.
to achieve decoupling, the next step is to do the corresponding relationship, I know which servcie in which Excelmapper is? Maybe we can write the corresponding logic ourselves. But I think the workable solution is to take advantage of Spring's IOC thinking. control Flip: Not my service to find which mapper, but which of my mapper to find which service. It's not that you're looking for me, but I'm looking for you so you don't have to write that complex correspondence. It is easier for you to look for you than to find you. Dependency Injection: What is injected? is an injection that relies on reference objects. Iexcelmapper is a quoted statement, how do I inject the object he is referring to? It's easy to write a properites file that shows their correspondence.
#本月excel映射excelMapper4CurrentMonth =com.springioc.mapper.impl.excelmapper4currentmonth# Monthly Excel Mapping Excelmapper4nextmonth=com.springioc.mapper.impl.excelmapper4nextmonthexcelservice4currentmonth= Com.springioc.service.excelserverexcelservice4cnextmonth= Com.springioc.service.excelserverexcelservice4currentmonth.excelmapper= Excelmapper4currentmonthexcelservice4cnextmonth.excelmapper=excelmapper4nextmonth

Have a correspondence relationship. The next step is how to deal with it. Spring is a container, the creation of objects, the establishment of dependencies should be given to the sring container to do. A spring container is written below.we can write the mapping 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;/** * Equivalent to a spring container for storing beans * @author Yj.shi * * /public class Container {private static map<string,object> map=new hashmap<string,object> ();p ublic Container () {Properties Properties=new properties (); InputStream in = null;try {In=container.class.getclassloader (). getResourceAsStream ("Ioc.properties");p roperties.load (in); for (Map.entry<object, object> 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 ();}}} /** * Map the contents of the properties * @param key * @param value * @throws classnotfoundexception * @throws ILLEGALACCEssexception * @throws instantiationexception * @throws nosuchmethodexception * @throws invocationtargetexception */PR ivate void Mappeingbean (String key,string value) throws Instantiationexception, Illegalaccessexception, ClassNotFoundException, InvocationTargetException, nosuchmethodexception{string[] parts=key.split ("\ \"); if (parts.length==1) {//Object creation Map.put (Parts[0],class.forname (value). newinstance ());} else{//Injection Reference Relationship Object Target=getbeanbyid (Parts[0]); object Resource=getbeanbyid (value); Propertyutils.setproperty (target, parts[1], Resource);}} /** * Through key past spring container data * @param key * @return */public static Object Getbeanbyid (String key) {return map.get (key);}


All right, let's just 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<string,string[][]> map=reader (null); for (String Key:map.keySet ()) {ExcelServer service= (excelserver) Container.getbeanbyid (key); Service.save (Map.get (key));}} /** * Read Excel into MAP *    key for sheet page name, value for the two-dimensional data that resolves the Exceld cell * @param file * @return */private static MAP<STRING,STR Ing[][]> Reader (file file) {map<string,string[][]> map=new hashmap<string,string[][]> ();// You can parse Map.put ("Excelservice4currentmonth", null) according to the name of the sheet page, map.put ("Excelservice4cnextmonth", null); return map;}}

Summary: SPRINGIOC control Rollover, is the role of the flip, from I want to actively find to wait for others to find me. What to do after finding me, to do is to rely on injection, the object I want through setter or construction method or interface way to me. The decoupling between class and class is realized, and the reference relation of dependent object is established. Double benefit, easy and enjoyable.the concrete implementation will be given to the spring container to do it. Code Link              

The first step of spring principle--importing Excel into columns to explore SPRINGIOC principle

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.