Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How springboot loads configuration files in jar packages

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains how springboot loads the configuration file in the jar package. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how springboot loads the configuration file in the jar package.

1. How to load the annotated classes in the jar package when springboot starts?

The Application class of springboot automatically scans the classes that load its package and its child package, but the classes in other package or jar are not automatically scanned, so you need to configure the scan path:

@ ComponentScan (basePackages = {"com.ysma.oschina", "com.ysma.csdn"}, / / specify package excludeFilters = {@ ComponentScan.Filter (value = Other.class, type= FilterType.ASSIGNABLE_TYPE)}) / / exclude individual classes public class OschinaApplication {public static void main (String [] args) {SpringApplication.run (Oschina.class, args);}} from the csdn jar package

The parameter meaning of @ ComponentScan annotation type

BasePackages: the parameter is the basic package for scanning annotated components

BasePackageClasses: an alternative to specifying scan comment package type safety for basepackages ()

ExcludeFilters: specifies the type that is not suitable for component scanning

IncludeFilters: specify which types are eligible for component scanning

LazyInit: specifies whether the scanned beans should be registered to initialize for lazy

UseDefaultFilters: indicates whether comments for classes are automatically detected

The types and meanings of FilterType in @ Filter

ANNOTATION: annotation typ

ASSIGNABLE_TYPE:ANNOTATION: specified type

ASPECTJ: according to Aspectj's expression, it is basically not used.

REGEX: according to regular expression

CUSTOM: custom rules need to be implemented with custom FilterType as follows:

Public class MyFilterType implements TypeFilter {@ Override public boolean match (MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {if (metadataReader.getClassMetadata (). GetClassName (). Contains ("Department")) {/ / get the information of the current class annotations AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata () For (String s: annotationMetadata.getAnnotationTypes ()) {System.out.println ("class annotation type currently being scanned" + s);} / / get information about the class currently being scanned ClassMetadata classMetadata = metadataReader.getClassMetadata (); System.out.println ("class name of the class currently being scanned" + classMetadata.getClassName ()) / / get the resource information of the current class (the path where the class is stored...) Resource resource = metadataReader.getResource (); System.out.println ("address of the class currently being scanned" + resource.getURL ()); return true;} return false;}}

2. Load resources in the jar package

Path problem overview.properties is placed in the config folder of the resource root directory

If the resource project path is not available, it will be automatically assigned to the project resource path where the jar package resides, such as / config/overview.properties

Resource classpath is not available, it will be automatically assigned to the project classpath where the jar package is located, such as config/overview.properties

The classpath path is feasible, and the classpath is automatically identified and loaded. For example, the classpath:config/overview.properties configuration file is placed in the classpath directory of the parent project at this time.

An example of ResourceUtil is as follows

Import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.IOUtils;import org.springframework.core.io.ClassPathResource;import org.springframework.util.ResourceUtils;import java.io.*;import java.net.URL;/** * Resource loading tool * this application is a jar package application. It mainly uses the classpath path * @ see this getClassPathFile * / @ Slf4jpublic class ResourceUtil {private static final String PATH_WINDOWS = "\"; private static final String PATH_LINUX = "/" / * * read the jar package file * @ param pathName path * @ return inputStream * @ throws FileNotFoundException * / public static URL getJarURL (String pathName) throws FileNotFoundException {try {ClassPathResource classPathResource = new ClassPathResource (pathName); return classPathResource.getURL () } catch (IOException e) {log.error ("ResourceUtil.getResourcePath file does not exist, path: {}", pathName); throw new FileNotFoundException (pathName + "file does not exist") }} / * the acquisition of files in the jar package * @ param classPath because of the sexual path problem, it is better to obtain the file classpath:config/overview.properties * @ throws FileNotFoundException ex * / @ Deprecated public static File getClassPathFile (String classPath) throws FileNotFoundException {try {return ResourceUtils.getFile (classPath) through classpath. } catch (FileNotFoundException e) {log.error ("ResourceUtil.getResourcePath file does not exist, path: {}", classPath); throw new FileNotFoundException (classPath + "file does not exist") }} / * get the file path * @ param path file path * @ return URL * / public static URL getResourcePath (String path) throws FileNotFoundException {try {/ / 1. Based on the Linux path, path = path.replaceAll (PATH_WINDOWS, PATH_LINUX); / * 2. Choose the loading method according to the beginning. First, the "/" represents the root directory of the project. For example, the project is called myproject, and "/" represents myproject. Second, there is no directory * / return path.startsWith (PATH_LINUX) that represents the current class. ResourceUtil.class.getResource (path): ResourceUtil.class.getClassLoader (). GetResource (path);} catch (Exception e) {log.error ("ResourceUtil.getResourcePath file does not exist, path: {}", path); throw new FileNotFoundException (path + "file does not exist") }} / * get the file * @ see # getJarURL (String path) * / public static File getJarFile (String path) throws FileNotFoundException {try {ClassPathResource classPathResource = new ClassPathResource (path); InputStream is = classPathResource.getInputStream (); File tempFile = File.createTempFile ("groovy", null); IOUtils.copy (is, new FileOutputStream (tempFile)) Return tempFile;} catch (IOException e) {log.error ("ResourceUtil.getResourcePath file does not exist, path: {}", path); throw new FileNotFoundException (path + "file does not exist");}

3. Classpath path problems as in 2 above. If the configuration file is placed in the jar package, the class address should be: classpath*:config/overview.properties

The difference between classpath and classpath*:

A:classpath: only look for files in your class path.

Class: contains not only the class path, but also the class path in the jar file to find it.

C: when a resource of the same name exists in multiple classpath and needs to be loaded, only the first one is loaded with classpath:, in which case you also need to use the classpath*: prefix.

Note: using classpath*: requires traversing all the classpath, so the loading speed is slow; therefore, when planning, you should plan the path where the resource files are located and avoid using classpath* as much as possible.

At this point, I believe you have a deeper understanding of "how springboot loads the configuration file in the jar package". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report