1. 程式人生 > >spring mvc 從bean中自動獲取物件

spring mvc 從bean中自動獲取物件

寫在前面

在日常開發或者學習spring mvc web專案中,當專案打包部署後,某些自定義配置項引數可能會需要改動。而這些配置項引數如果被寫死進專案中,或許會造成很大的麻煩。因此,有時候這些需要變動的自定義的配置項引數,便需要寫進配置檔案中。spring mvc 中有一個bean物件的概念,具體含義以及原理,各位猿友可自行腦補。
今天小編就向大家介紹一種從配置檔案中自動裝配bean物件池中物件的知識點。

專案需求

圖片上傳,上傳圖片在伺服器中上傳路徑的配置。

spring-mvc.xml 檔案bean的配置

<!--上傳檔案配置-->
    <bean id
="uploadConfig" class="com.qingyu.blog.util.UploadConfigFactoryBean">
<property name="uploadPath" value="D:\image" /> <property name="thumbDir" value="thumbs" /> <property name="thumb" value="0.3" /> <property name="imageFormat" value=".jpg"/> </bean
>

UploadConfigFactoryBean.java

package com.qingyu.blog.util;


import org.springframework.beans.factory.FactoryBean;

/**
 * @author longping jie
 * @name UploadConfig
 * @description the class is used to 上傳檔案的配置
 * @date 2017/11/10
 */
public class UploadConfigFactoryBean implements FactoryBean<UploadResolver> {
    //預設上傳位置
private String uploadPath; //儲存縮圖的資料夾名 private String thumbDir; //預設縮略比例 private double thumb; //預設統一儲存格式 private String imageFormat; public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public String getThumbDir() { return thumbDir; } public void setThumbDir(String thumbDir) { this.thumbDir = thumbDir; } public double getThumb() { return thumb; } public void setThumb(double thumb) { this.thumb = thumb; } public String getImageFormat() { return imageFormat; } public void setImageFormat(String imageFormat) { this.imageFormat = imageFormat; } @Override public UploadResolver getObject() throws Exception { UploadResolver r = new UploadResolver(); r.uploadConfig = this; return r; } @Override public Class<?> getObjectType() { return UploadResolver.class; } @Override public boolean isSingleton() { return false; } }

UploadResolver .java

package com.qingyu.blog.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @author longping jie
 * @name UploadResolver
 * @description the class is used to 上傳圖片的工具類
 * @date 2017/11/10
 */
public class UploadResolver {
    UploadConfigFactoryBean uploadConfig;
    String dateName;

    public UploadResolver() {
        LocalDate dt = LocalDate.now();
        int year = dt.getYear();
        int month = dt.getMonthValue();
        int date = dt.getDayOfMonth();

        String monthStr = month + "";
        String dateStr = date + "";

        if (month < 10) {
            monthStr = "0" + monthStr;
        }
        if (date < 10) {
            dateStr = "0" + date;
        }
        dateName = String.format("%s-%s-%s", year, monthStr, dateStr);
    }

    /**
     * 按比例縮小圖片
     *
     * @param image 需要上傳的圖片
     * @return
     */
    public String saveThumbImage(MultipartFile image) {
        String imageName = createImageName();
        String thumbName = createThumbImageName();
        File imageFile = new File(imageName);
        File thumbFile = new File(thumbName);

        if (!imageFile.getParentFile().exists()) {
            imageFile.getParentFile().mkdirs();
            thumbFile.getParentFile().mkdirs();
        }

        try {
            image.transferTo(imageFile);
            Thumbnails.of(imageFile).scale(0.3f).toFile(thumbFile);//按比例縮小
        } catch (IOException e) {
            e.printStackTrace();
        }


        return thumbName;
    }

    /**
     * 裁剪圖片
     *
     * @param image 需要上傳的圖片物件
     * @param args  圖片裁剪引數
     * @return
     */
    public String saveThumbImage(MultipartFile image, CutImageArgs args) {
        String imageUrl = "";
        String imageName = createImageName();
        String thumbName = createThumbImageName();
        File imageFile = new File(imageName);
        File thumbFile = new File(thumbName);

        if (!imageFile.getParentFile().exists()) {
            imageFile.getParentFile().mkdirs();
            thumbFile.getParentFile().mkdirs();
        }

        try {
            image.transferTo(imageFile);
            BufferedImage buf = Thumbnails.of(imageFile).width(args.getPresentWidth()).height(args.getPresentHeight())
                    .asBufferedImage();
            Thumbnails.of(buf).sourceRegion(args.getX(), args.getY(), args.getW(), args.getH())
                    .size(args.getNeed_w(), args.getNeed_h()).toFile(thumbFile);
            imageUrl = thumbName;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageUrl;

    }

    /**
     * 建立一個源圖片上傳的路徑名
     *
     * @return
     */
    private String createImageName() {
        String fileName = createUUIDName();
        String imageName = String.format("%s%s%s%s%s%s", uploadConfig.getUploadPath(), File.separator,
                dateName, File.separator, fileName, uploadConfig.getImageFormat());
        return imageName;
    }

    /**
     * 建立一個壓縮圖片上傳的路徑名
     *
     * @return
     */
    private String createThumbImageName() {
        String fileName = createUUIDName();
        String thumbName = String.format("%s%s%s%s%s%s%s%s", uploadConfig.getUploadPath(), File.separator,
                dateName, File.separator, uploadConfig.getThumbDir(),
                File.separator, fileName, uploadConfig.getImageFormat());

        return thumbName;
    }

    /**
     * 用uuid重新命名檔案
     *
     * @return 檔案新的名字
     */
    private String createUUIDName() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


}
@Controller
@RequestMapping("/user")
public class UserController implements BeanFactoryAware {
    private Logger logger = LogManager.getLogger(UserController.class);
    @Autowired
    UserLoginService userLoginService;
    @Autowired
    SystemService systemService;
    @Autowired
    UploadResolver uploadResolver;

    .....中間程式碼省略


    BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

相關推薦

spring mvc bean自動獲取物件

寫在前面 在日常開發或者學習spring mvc web專案中,當專案打包部署後,某些自定義配置項引數可能會需要改動。而這些配置項引數如果被寫死進專案中,或許會造成很大的麻煩。因此,有時候這些需要變動的自定義的配置項引數,便需要寫進配置檔案中。spring m

spring MVC 怎麼定義bean建立的物件是不是單例

Spring 中的 bean bean 是根據 scope 來生成的,表示 bean 的作用域。 scope 有 4 種類型,具體如下。 singleton:單例,表示通過 Spring 容器獲取的該物件是唯一的。 prototype:原型,表示通過 Spring 容器獲取的物件是不

如何在spring普通的bean獲取session物件

在使用spring時,經常需要在普通類中獲取session,request等物件。 比如在一些AOP攔截器類,在有使用struts時,因為struts2有一個介面使用org.apache.stru

Spring+Quartz 資料庫獲取定時任務和定時時間,動態實現對定時任務的增刪改查

本文轉載自部落格:http://blog.csdn.net/wwkms/article/details/48851005 ----------------------------------------------------------------------------------------

JSON自動生成對應的物件模型

> 程式設計的樂趣和挑戰之一,就是將體力活自動化,使效率成十倍百倍的增長。 ##需求 做一個專案,需要返回一個很大的 JSON 串,有很多很多很多欄位,有好幾層巢狀。前端同學給了一個 JSON 串,需要從這個 JSON 串建立對應的物件模型。 比如,給定 JSON 串: ```java {"error":

spring mvc@ResponseBody取到json發現中文亂碼

tab reat builder attr cover proc first hresult acc   問題背景:如題。   問題定位:代碼跟蹤,從源頭入手,一步一步跟進,直到設置中文編碼的地方。   問題代碼: /** * 獲取單個測試樁接口內容

Ubuntu 16.04使用“互聯網自動獲取”時間無法寫入硬件BIOS的奇怪問題

同步 最新 寫入 不能 如果 方法 body 自動獲取 log 目前發現的就是這個問題,只能手動同步到BIOS。 如果是手動設置過時間,那麽可以正常同步到BIOS。 而如果切換到從互聯網自動獲取時間時,是不能同步到BIOS的,但是界面上的時間確實最新的。 解決方法:

Spring MVC Controller向頁面傳值的方式

用戶 () 傳參數 control let att model enter 設定 Spring MVC 從 Controller向頁面傳值的方式 在實際開發中,Controller取得數據(可以在Controller中處理,當然也可以來源於業務邏輯層),傳給頁面,常用的方

Spring 自定義Bean 實例獲取

pan 定義 turn get 漏洞 封裝 @override stat public 一、通過指定配置文件獲取, 對於Web程序而言,我們啟動spring容器是通過在web.xml文件中配置,這樣相當於加載了兩次spring容器 ApplicationContext

解決Spring MVC @ResponseBody返回文字符串亂碼問題

有效 per log bean dia media converter 原因 ons 引起亂碼原因為spring mvc使用的默認處理字符串編碼為ISO-8859-1 具體參考org.springframework.http.converter.StringHttpMess

Spring MVC(十三)--保存並獲取屬性參數

信息 sta ams val esp 路徑 也會 user 方法 這裏的屬性參數主要是指通過request、session、cookie等設置的屬性,有時候我們需要將一些請求的參數保存到HTTP的request或者session對象中去,在控制器中也會進行設置和獲取操作,s

Spring MVC(三)控制器獲取頁面請求引數以及將控制器資料傳遞給頁面和實現重定向的方式

首先做好環境配置 在mvc.xml裡進行配置   1.開啟元件掃描   2.開啟基於mvc的標註   3.配置試圖處理器 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www

JAVA---面向物件生活抽取例項物件

public class Car{ private String brand; private int num; private String colour; private int seats; //建構函式 public Car(String brand){

Spring Mvc 前臺數據的獲取、SpringMvc 表單數據的獲取

lte 方法 gmv servlet val pri 編碼 XML 用戶 首先在web.xml 裏面配置一個編碼過濾器 1 <!-- springmvc框架本身沒有處理請求編碼,我們自己配置一個請求編碼過濾器 --> 2 <filter>

.net core依賴注入容器獲取物件

建立引擎方法:改方法用於在不使用構造注入的情況下從依賴注入容器中獲取物件 /// <summary> /// 一個負責建立物件的引擎 /// </summary> public interface IEngine { T Res

Spring MVC : Model和View名稱生成最終的View

當我們使用 Spring MVC開發Web應用頁面時,一般會使用某種檢視模版引擎技術,比如FreeMarker,Velocity之類的,然後還會寫很多控制器方法用來處理某個請求,這些控制器方法基本的套路是: 寫一個檢視模板,配置到合適的位置; 控制器方法接收處

Spring MVC實際專案的應用

目前的專案應用了Spring MVC框架,總結一下實際應用中這個框架是如何發揮作用的,下圖是處理流程。參考 1: 首先使用者傳送請求資訊,例如url:http://ggg-admin.inta.sit.fan.com/advertisement/query

Spring boot 梳理 - SpringBoot注入ApplicationContext物件的三種方式

直接注入(Autowired) @Configuration public class OAConfig { @Autowired private ApplicationContext applicationContext; @B

Spring mvc整合Mybatis,選擇性儲存物件欄位資料

前言 我們平時使用mybatis儲存物件資料時,經常可能只是修改其中某一倆個欄位的值,這個時候,我們為了減少資料庫更新帶來的效能、行鎖等不必要的消耗,可能會重新寫一個介面,只負責修改需要修改的值。 但是,隨著業務系統的變更,業務欄位的增加,越來越多的欄位需要

Spring mvc 零搭建

以eclipse 為例一:new Dynamic Web Project(如果沒有web.xml,輸入完專案名點下一步,勾選Generate web.xml deployment descriptor)二:在WebContent 寫一個靜態頁面 hello.html(試試we