Optimize an upload feature into a starter

Quickly create a SpringBoot project pom.xml as follows:

The following three dependencies are required:

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>
Copy the code

Provides an interface for uploading files, IUploadService

Public interface IUploadService {/** * @param file * @return */ Result upload(MultipartFile file); . }Copy the code

Properties corresponding class:

/ / @component@configurationProperties (prefix = "spring.upload") public class UploadProperties {private String dir; // File prefix private String prefix; //getter and setter }Copy the code

Default implementation method:

public class DefaultUploadService implements IUploadService { @Autowired private UploadProperties uploadProperties; public DefaultUploadService (UploadProperties uploadProperties){ this.uploadProperties=uploadProperties; } / * * * * / @ file upload method Override public Result upload (MultipartFile file) {if (uploadProperties. GetDir () = = null | | UploadProperties. GetPrefix () = = null) {return Result. The error (" please upload path configuration files "); } try {if(file.isempty ()){return result.error (" the file isEmpty "); } String originalFilename=file.getOriginalFilename(); boolean blob = originalFilename.equals("blob"); String fileExt = blob?" .jpg": originalFilename.substring(originalFilename.lastIndexOf(".") ).toLowerCase(); if(StringUtils.isBlank(fileExt)||fileExt.equals(".blob")){ fileExt=".jpg"; } String month= DateUtil.formatDate(new Date(),"yyyyMMdd"); String uploadPathPrefix=uploadProperties.getPrefix()+month+"/"; SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = UUID.randomUUID() + fileExt; String absuDir=uploadProperties.getDir()+uploadPathPrefix; AbsuDirFile =new File(absuDir); if(! absuDirFile.exists()){ absuDirFile.mkdirs(); } // File uploadFile=new File(absuDir,newFileName); Files.copy(file.getInputStream(), uploadFile.toPath()); NameUrlBean bean=new NameUrlBean(); bean.setName(originalFilename); bean.setUrl(uploadPathPrefix+newFileName); return Result.success(bean); } catch (IOException e) { e.printStackTrace(); Return result. error(' failed to upload file '+ LLDB etMessage()); }}... }Copy the code

UploadConfig

/** * @conditionalonProperty (name = "dir",prefix = "spring.upload") * when importing this jar project need to configure spring.upload @Configuration @EnableConfigurationProperties(UploadProperties.class) @ConditionalOnProperty(name = "dir",prefix = "spring.upload") public class UploadConfig { @Autowired private UploadProperties uploadProperties; @Bean public DefaultUploadService defaultUploadService(){ return new DefaultUploadService(uploadProperties); }}Copy the code

@conditionalonproperty (name = “dir”,prefix = “spring.upload”) This class is registered with the container only when the project importing the upload jar is configured with the upload file address spring.upload.dir in application.yml.

“/ meta-INF /spring.factories”

#-------starter --------- org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.it520.upload.config.UploadConfigCopy the code

Add the following to project POM.xml:

<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId>  <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build>Copy the code

The default springBoot project does not have a configuration for this node. This configuration needs to be added here otherwise the jar file path generated after packaging will not be found.

The complete Stater project is as follows:

In this springBoot project we do not need to start the classes and the original application files and test directories, so we can delete them here.

Idea Click Install to package the project and store it in a local Maven repository

Use test:

Pick a random springBoot project and introduce our custom stater as follows:

Add a new interface to use the default DefalutUploadService to upload files

@RestController public class UploadTestController { @Autowired private DefaultUploadService uploadService; @PostMapping("/myUpload") public Result upload(@RequestParam("file") MultipartFile file){ return uploadService.upload(file); }}Copy the code

We start the project when we do not configure the address of the upload file in the application file:

When starting the project, @AutoWired could not find the DefaultUploadService bean in the container, so the startup failed

In application. Yml, we configure the address to upload the file:

#other setting

spring.upload.dir=D:/upload
spring.upload.prefix=/test/

#other setting
Copy the code

After the configuration, restart the project and no error will be reported. Test access to the interface just defined to upload files, as shown in the following figure:

By now, we have created a custom stater, which can be uploaded to the Maven private server repository. When we need to upload files in future projects, we can import this JAR and call the default implementation method.