Friday, December 11, 2015

通用的Spring自动装配机制



通用的Spring自动装配机制
我们经常在写项目的时候提交表单,表单信息可能有非常多个。这样我们在Controller里面就要一个一个在方法参数里面罗列出来非常不方便。怎么办呢?
马上有人说,写个Java bean呗。
可是你有没有想过,写一个还好,难道你一有需求就要写一个bean?而且很多的我们只是为了自动装配目的,并没有实际的需求。这样泛滥的bean无论是对于架构还是代码可读性都是非常不友好的。

解决办法

既然bean是一个键值对,那么我们是不是可以写一个类似的Map,String对应bean的Name,value对应相应的值,这样在后台使用的时候一个一个取出来不就可以了吗?
前端代码:
Auto-File
<body>
    <form action="autoFill" method="post">
        <label>userName:</label><input type="text" name="params[userName]"/>
        <labele>passWord:</labele><input type="text" name="params[passWord]"/>
        <input type="submit"/>
    </form>
</body>
</html>
这段代码非常的简单,一个有账号和密码的提交表单。注意这里的name。我们给它这样的表述: params[userNmae] 其中这里的params可以是任意的字段,因为我们这里是要告诉后台这是一个Map参数,userName对应一个Key,而input的Value对应一个值。
public class BaseQuery {
protected Map<String,Object> params = new HashMap<String,Object>();

public Map<String, Object> getParams() {
    return params;
}

public void setParams(Map<String, Object> params) {
    this.params = params;
}
}
我们用一个Map来获取所有前端的键值对,并且将其存储。
最后看一下Spring Controller中的代码:
@RequestMapping(value = "/autoFill" , method = RequestMethod.POST)
  public void autoFill(BaseQuery query){
  System.out.println(query.getParams());
  }
输出的结果是:{userName=user, passWord=pass}
user和pass是我在前端的输入值。

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts