Spring Boot(7)--Uploading Files(Lambda,匿名內部類,上傳文件 )

springboot的總官方學習文檔

本次本章對應的官方文檔

準備

這次嘗試自己新建一個項目,按照要求添加這兩個依賴。
在這裏插入圖片描述
新建一個文件夾storage(在demo裏面新建的文件夾,其實就對應一個包)
在這裏插入圖片描述
新建完發現下面沒有出現我們新建的storage文件夾,F5刷新一下就出來了
官網github提供的初始的項目就包含了storage包裏面的文件,我是直接複製古來的,一個個新建太麻煩了

新建個FileUploadController.java的控制類在這裏插入圖片描述

然後FileUploadController.java寫入對應的代碼

然後新建一個網頁的html
在這裏插入圖片描述

添加文件大小限制
在這裏插入圖片描述

記得在添加bean否則如下報錯


APPLICATION FAILED TO START


Description:
Parameter 0 of constructor in com.example.demo.storage.FileSystemStorageService required a bean of type ‘com.example.demo.storage.StorageProperties’ that could not be found.

Action:
Consider defining a bean of type ‘com.example.demo.storage.StorageProperties’ in your configuration.

然後訪問http://localhost:8080/ 網址就好了。
在這裏插入圖片描述

@EnableConfigurationProperties(StorageProperties.class)
以及
先說下面這段代碼吧,再記錄一下,希望每次理解都能更深入點

	@Bean
	public CommandLineRunner mingZiSuiBian(StorageService storageService) {
		return (args) -> {
			storageService.deleteAll();
			storageService.init();
		};//重寫run方法  
	}

Bean這個解釋如下圖
在這裏插入圖片描述
@Bean 表明一個產生bean的方法,並且這個方法會被Spring container管理。
官方給的在Spring XML 的示例如下:
@Bean
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;//最後還是返回了一個MyBean 對象 obj
}
所以

	@Bean
	public CommandLineRunner 名字隨意啦(StorageService storageService) {
		return (args) -> {
			storageService.deleteAll();
			storageService.init();
		};//重寫了run方法  ,並且返回了利用Lambda表達式實現實例化函數式接口的對象
	}

另外一種寫法,不利用Lambda表達式,直接新建一個繼承CommandLineRunner接口的類就行,並且再重載run函數。這種方法是之前常用的方法
在這裏插入圖片描述
@Component註釋聲明 MyStartupRunner1類作爲CommandLineRunner接口的Component,會在spring bean初始化之後,SpringApplication run之前執行,可以控制在項目啓動前初始化資源文件,比如初始化線程池,提前加載好加密證書等
作者:低調小熊貓
鏈接:https://www.jianshu.com/p/7e16f1b59ced
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
還可以參考CommandLineRunner的使用,我直接賦到最後了

然後對於
@Autowired
private StorageService storageService; //StorageService 是一個接口

在這裏插入圖片描述
Autowired註釋會自動注入這個接口的一個實現,在本次程序之中,只有FileSystemStorageService這一個實現
在這裏插入圖片描述

我們可以設置一個斷點,然後debug,會發現運行到了FileSystemStorageService實現裏面了
在這裏插入圖片描述

其中有個@Autowired的要注意
在這裏插入圖片描述
其中StorageProperties的代碼如下圖
在這裏插入圖片描述
關於這種用法,在官網中的介紹如下(網址) 中文翻譯直接加粗了
3.5. Spring Beans and Dependency Injection

You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using @ComponentScan (to find your beans) and using @Autowired (to do constructor injection) works well.
你能任意使用Spring框架技術的定義你的beans和這些beans的注入依賴。爲了方便,我們通常使用@ComponentScan (來發現你的beans)並且使用@Autowired(來構建注入)

If you structure your code as suggested above (locating your application class in a root package), you can add @ComponentScan without any arguments. All of your application components (@Component, @Service, @Repository, @Controller etc.) are automatically registered as Spring Beans.
如果你像上面建議的方式(在你的根包的應用類中)構建你的代碼,你能夠添加@ComponentScan而不需要其他的聲明。所有你的應用組件(@Component, @Service, @Repository, @Controller etc註釋的類)是自動作爲 Spring Beans註冊。

The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:
下面的例子,顯示了一個 @Service Bean使用 構造注入 來獲得一個需要的 RiskAssessor bean

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    @Autowired
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

然後說一下FileSystemStorageService這個類
關於@Service參考了下面網址Spring註解@Component、@Repository、@Service、@Controller區別

SpringMVC的四個基本註解annotation(控制層,業務層,持久層)–@Component,@Repository@Service,@Controller

spring三層示例controller層,service層示例,dao層示例,完全代碼

spring 2.5 中除了提供 @Component 註釋外,還定義了幾個擁有特殊語義的註釋,它們分別是:@Repository、@Service 和 @Controller。這 3 個註釋分別和持久層、業務層和控制層(Web 層)相對應。
@Repository持久層組件,用於標註數據訪問組件,即DAO組件
@Controller用於標註控制層組件(如struts中的action)
@Service 此注註解屬於業務邏輯層
@Component泛指組件,是上面三個的老大哥,當組件不好歸類的時候,我們可以使用這個註解進行標註。

示例:

1.  控制層
@Controller // 註釋爲controller
@RequestMapping("/login")
public class LoginAction {
//假如,有兩個類來實現一個接口,會出現衝突的問題。寫了參數,它就不衝突了,
 repository(value="a")。
 
 @Autowired      
 @Qualifier("userService") //註釋指定注入 Bean 
 private IUserService userService;
 。。。。。。 其他略 。。。。。。
}
2.  業務邏輯層     對數據庫返回的數據進行一系列操作
@Service("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    @Qualifier("userDao")
    private IUserDao userDao;  
 。。。。。。 其他略 。。。。。。
}

3.  持久層 就是訪問數據庫的數據並返回

@Repository("userDao")
public class UserDaoImpl implements IUserDao {
 private static Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
 private DataSource dataSource;  
    private JdbcTemplate template;  
      
    @Autowired  
    public UserDaoImpl(DataSource dataSource){  
        this.dataSource= dataSource;  
        template = new JdbcTemplate(this.dataSource);  
    }
 。。。。。。 其他略 。。。。。。

}

關於@Service(student) 括號裏面student是你自己定義的bean名字,Spring自動根據bean的類名實例化一個首寫字母爲小寫的bean,例如Chinese實例化爲chinese

這是的student是要實現的類的一個對象名而已,比如在一個Student實現類上加@Service(“student”),括號裏面就是給實例化後的Student對象取個名字。這是在一個接口有多個實現類的情況下區分實現類的方式。

比如在service中 Student實現了Person接c口,在controller裏面@Autowired Person時,假如這時Person還有另一個實現類User,爲了確定實例化Student還是User, @Service括號裏面的東西就有用了。

在@controller裏面
@Autowired
@Qualifier(“student”)
private Person person;

這樣就確定實例化了一個person指向一個Student對象

這篇寫的夠多了,關於thymeleaf網頁下一個文章來學習吧


CommandLineRunner
1.兩種實現方式

  • 1.1繼承CommandLineRunner接口
  • 2.爲什麼要使用CommandLineRunner

springboot的 CommandLineRunner 接口主要用於實現應用初始化之後,去執行一段邏輯代碼,並且在整個項目的聲明週期中,執行一次,源碼如下:

package org.springframework.boot;

public interface CommandLineRunner {
    void run(String... var1) throws Exception;
}

1.兩種實現方式
1.1繼承CommandLineRunner接口
和註解 @Componerent一起使用,如果涉及到多個,用@Order()註解去設置執行順序

@Component
@Order(value = 1)
public class CLR1 implements CommandLineRunner{
public void run(String... strings) throws Exception {
     //do something
   }
}

@Component
@Order(value = 2)
public class CLR2 implements CommandLineRunner{
public void run(String... strings) throws Exception {
     //do something
   }
}

1.2 和@Bean連用,返回CommandLineRunner實例

@Bean   //initialize這個函數名無所謂
public CommandLineRunner initialize(SomeModel ModelInstance) {
    return (abc) -> {
        ModelInstance.dosomething(...)
    };
}


該方法需要放在有@Component/@SpringBootApplication註解的類上
abc爲任意字符,SomeModel ModelInstance 爲用Spring bean對象,controller中可用@Resource@Autowired接收

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章