Home Database Mysql Tutorial 品味Spring 的魅力_MySQL

品味Spring 的魅力_MySQL

Jun 01, 2016 pm 02:07 PM
bean public use method question charm

Spring

  
  Spring的哲学是在不影响Java对象的设计的情况下将Java对象加入到框架中。

  EJB的框架采用了一种侵略性(Invasive)的方法来设计对象,它要求你在设计中加入符合EJB规范的代码。一些轻量级的COP框架,例如Avalon,也要求对象设计时必须符合某种规范,例如Serviceable接口,这种做法是典型的Type 1做法。

  这种设计思路要求Spring采用一种动态的、灵活的方式来设计框架。所以spring大量采用了反射。首先spring要解决的一个问题就是如何管理bean。因为IOC的思想要求bean之间不能够直接调用,而应该采用一种被动的方式进行协作。所以bean的管理是spring中的核心部分。

  反射和内省在代码的层次上思考问题,有时候能够带来出人意料的灵活性。但它的使用有时候也是一个哲学问题,不论是在ORM设计还是在AOP设计上都出现了类似的问题-究竟是使用反射,还是使用代码生成。

  在Spring中,处理这个问题的核心是在org.springframework.beans包中。而其中最为核心的部分,则是BeanWrapper。BeanWrapper,顾名思义,就是bean的包装器。所以,它的主要工作,就是对任何一个bean,进行属性(包括内嵌属性)的设置和方法的调用。在BeanWrapper的默认实现类BeanWrapperImpl中,虽然代码较长,但完成的工作却是非常的集中的。

  BeanWrapper的深入研究

  我们看看这个BeanWrapper是如何发挥运作的,假设我们有两个bean:

  public class Company {
  private String name;
  private Employee managingDirector;

  public String getName() {
  return this.name;
  }
  public void setName(String name) {
  this.name = name;
  }
  public Employee getManagingDirector() {
  return this.managingDirector;
  }
  public void setManagingDirector(Employee managingDirector) {
  this.managingDirector = managingDirector;
  }
  }

  public class Employee {
  private float salary;

  public float getSalary() {
  return salary;
  }
  public void setSalary(float salary) {
  this.salary = salary;
  }
  }

  然后我们使用BeanWrapper来调用这两个bean:

  Company c = new Company();
  BeanWrapper bwComp = BeanWrapperImpl(c);
  // setting the company name...
  bwComp.setPropertyValue("name", "Some Company Inc.");
  // ... can also be done like this:
  PropertyValue v = new PropertyValue("name", "Some Company Inc.");
  bwComp.setPropertyValue(v);

  // ok, let's create the director and tie it to the company:
  Employee jim = new Employee();
  BeanWrapper bwJim = BeanWrapperImpl(jim);
  bwJim.setPropertyValue("name", "Jim Stravinsky");
  bwComp.setPropertyValue("managingDirector", jim);

  // retrieving the salary of the managingDirector through the company
  Float salary = (Float)bwComp.getPropertyValue("managingDirector.salary");

  看起来麻烦了许多,但是这样spring就可以使用统一的方式来管理bean的属性了。


  Bean的制造工厂

  有了对单个Bean的包装,还需要对多个的bean进行管理。在spring中,把bean纳入到一个核心库中进行管理。bean的生产有两种方法:一种是一个bean产生多个实例,一种是一个bean只产生一个实例。如果对设计模式熟悉的话,我们就会想到,前者可以采用Prototype,后者可以采用Singleton。

  注意到,反射技术的使用使得我们不再像原始的工厂方法模式那样创建对象。反射可以非常灵活的根据类的名称创建一个对象。所以spring只使用了Prototype和Singleton这两个基本的模式。

  spring正是这样处理的,但是我们希望用户能够维护统一的接口,而不需要关心当前的bean到底是Prototype产生的独立的bean,还是Singleton产生的共享的bean。所以,在org.springframework.beans.factory包中的BeanFactory定义了统一的getBean方法。

  JDBC再封装JDBC优雅的封装了底层的数据库,但是JDBC仍然存在诸多的不变。你需要编写大量的代码来完成CRUD操作,而且,JDBC无论是遇到什么样的问题,都抛出一个SQLException,这种做法在异常使用上被称为不完备的信息。因为问题可能是很复杂的,也许是数据库连接的问题,也许是并发控制的问题,也许只是SQL语句出错。没有理由用一个简单的SQLException就搞定全部的问题了,这种做法有些不负责任。针对这两个问题,Spring Framework提出了两种解决方法:首先,提供一个框架,把JDBC应用中的获取连接、异常处理、释放等比较通用的操作全部都集中起来,用户只需要提供特定的实现就OK了。实现的具体细节采用的是模板方法。举个例子,在org.springframework.jdbc.object包中,MappingSqlQuery类实现了将SQL查询映射为具体的业务对象。JavaDoc中这样写到:Reusable query in which concrete subclasses must implement the abstract mapRow(ResultSet, int) method to convert each row of the JDBC ResultSet into an object. 用户必须实现mapRow方法,这是典型模板方法的应用。我们拿一个具体的例子来看看:

  class UserQuery extends MappingSqlQuery {

  public UserQuery(DataSource datasource) {
  super(datasource, "SELECT * FROM PUB_USER_ADDRESS WHERE USER_ID = ?");
  declareParameter(new SqlParameter(Types.NUMERIC));
  compile();
  }

  // Map a result set row to a Java object
  protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
  User user = new User();
  user.setId(rs.getLong("USER_ID"));
  user.setForename(rs.getString("FORENAME"));
  return user;
  }

  public User findUser(long id) {
  // Use superclass convenience method to provide strong typing
  return (User) findObject(id);
  }
  }

  其次是第二个问题,最麻烦的地方应该说是需要截住JDBC的异常,然后判断异常的类型,并重新抛出异常。错误的问题可以通过连接来获取,所以麻烦的是如何截获异常。Spring Framework采用的方法是回调,处理回调的类在Spring Framework中被称为template

  JdbcTemplate template = new JdbcTemplate(dataSource);
  final List names = new LinkedList();
  template.query("SELECT USER.NAME FROM USER",
  new RowCallbackHandler() {
  public void processRow(ResultSet rs) throws SQLException {
  names.add(rs.getString(1));
  }
  });

  回调函数是一个匿名类,其中也使用了模板方法,异常的处理都在父类中完成了。

  层间松耦合

  在开放源码界已经出现了大量的基于MVC的Web容器,但是这些容器都仅限于Web的范围,不涉及Web层次后端的连接,spring作为一个整体性的框架,定义了一种Web层和后端业务层的连接方式, 这个思路仍然疏运图MVC的范畴,但耦合更松散,不依赖于具体的集成层次。

  public class GoogleSearchController
  implements Controller {

  private IGoogleSearchPort google;

  private String googleKey;

  public void setGoogle(IGoogleSearchPort google) {
  this.google = google;
  }

  public void setGoogleKey(String googleKey) {
  this.googleKey = googleKey;
  }

  public ModelAndView handleRequest(
  HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
   String query = request.getParameter("query");
   GoogleSearchResult result =
   // Google property definitions omitted...

   // Use google business object
   google.doGoogleSearch(this.googleKey, query,start, maxResults, filter, restrict, safeSearch, lr, ie, oe);

   return new ModelAndView("googleResults", "result", result);
  }
  }

  回调函数是一个匿名类,其中也使用了模板方法,异常的处理都在父类中完成了。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

See all articles