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

Case study of jar package in java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "case study of jar package in java". In daily operation, I believe that many people have doubts about the case study of jar package in java. The editor has consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "case study of jar package in java". Next, please follow the editor to study!

Encounter slot point

In development practice, for the development of a jar package, many people just complete the function, as long as there is no problem with the use of the function, even if it is done, but it is far from enough. When using jar packages, users may encounter the following problems:

Missing documents, how to use a function, often need to spend half a day to a day looking for the person in charge, step by step communication, it is a waste of time

Dependency conflict, I just referenced a user authentication package and ended up bringing in all the SpringMVC, Jersey and Struts2 it supports

The method does not know the parameter name at all. An interface with three parameters. I have to face the document to know what they mean. If there is no document, I have to communicate with the person in charge or guess one by one.

Integration with Spring is very unfriendly, for example, initialization configuration forces the file to be full path.

Because I often encounter such slots, I pay special attention when writing common component packages.

Here I summarize the following seven suggestions for improvement. If you also want to provide the jar package for others to use, you can refer to it. Improve yourself for the convenience of others.

Document

As a public jar package, many projects may be used, if you do not have documentation, then every time someone wants to use it, they will ask you for all kinds of questions, which will waste both their own time and everyone's time. And the more people use it, you will find that they always ask those questions: how to use this? You support multiple implementations, which one should I choose? How to apply for use?

If you have a simple document, you can solve most of the problems.

A qualified document should contain the following:

Describe the function of this module in one sentence

Start quickly, showing how to get started with the easiest way to get started

Notes and frequently asked questions

Contact information of the person in charge

Be sure to update the document in time, if there is a problem that is not described in the document, users come to us to solve, remember to record this solution in common problems, for future users as a reference.

In fact, a document, in the final analysis, is to reduce your workload. Just imagine, if someone asks you all kinds of "trivial" things every day, you have to spend a lot of time communicating, and sometimes poor communication will hurt you. If you provide a document, it will be easier for everyone.

Minimum dependence

Do not rely on it if it is not necessary. Remember to use provided if it is necessary, but not necessary.

For example, our jar package provides the ability to quickly integrate Spring, so we need to add Spring-related dependencies, but this dependency is optional, so you can set it like this:

Org.springframework spring-context 5.1.8.RELEASE provided

Adding provided means that this dependency is not added to the jar package when it is packaged, but needs to be introduced by the user himself.

The advantage of a small setting is that if the user does not intend to integrate with Spring, then he will not indirectly introduce Spring dependencies. This is very important in a large project, when there are more external dependencies in a project, if there is a conflict between external dependencies, it will be very difficult to resolve.

Attach source code

I don't know if you have ever referenced a jar package, and when you were ready to start using it, the code prompts were all var1, var2, var3 and so on. You were dumbfounded when you clicked in:

At this time, IDEA kindly asked you, do you want to download the source code (Download Sources) to have a look? You're looking forward to it, Download! Results:

If I can't download it, ask me if I want to download it. Are you kidding me?

Imagine if your users will complain the same way when using your jar package. So how to solve it?

In fact, it is very simple, just add the maven-source-plugin plug-in to the pom file.

Org.apache.maven.plugins maven-source-plugin 3.0.1 attach-sources jar

This allows you to add the source package at compile time and automatically bring the source code when it is published to the maven repository. When using IDEA, users can download and associate the source code directly. Because of the relevance of the source code, the comments you write on it can also be seen by the user, which is much easier to use than documentation.

-parameters parameter

The Parameter class has been added to the reflection of Java8, so that we can get the method parameter information, including the parameter name, through reflection during the program run. But you need to add the-parameters parameter when the program is compiled. As a jar package, if we don't add this parameter when compiling, the user will never be able to get the parameter name through reflection! This may cause great inconvenience on some occasions.

In fact, adding the-paramters parameter is very simple. We just need to add the maven-compiler-plugin plug-in to the pom file and set parameters to true:

Org.apache.maven.plugins maven-compiler-plugin 3.8.0 ${java.version} ${java.version} true UTF-8 Interface oriented programming

As a public jar package, we need to provide a common function for each project, and once these functions are provided, we need to ensure compatibility, otherwise each upgrade will be difficult.

Therefore, we should enter into an "agreement" with the user, that is, an agreement through the interface, declaring that "I provide you with these capabilities and are responsible for them, and you do not need to pay attention to my underlying implementation, you just need to use them in accordance with the agreement." Note the scenarios and considerations in the API comments, because we added the source code package before, so users can directly associate and see the comments we have written, such as:

A more extreme approach is that we are only responsible for the interface. We can hide the implementation class (making it private at the package level) and then provide the implementation of the interface through the factory method instead of letting the user new himself.

After doing this, if we need to extend, or as the technology upgrades, we need to replace the underlying implementation, we do not need to worry about the compatibility in the implementation class, we just need to provide a new implementation class that implements the same interface. just let the factory method return the new implementation. And the old implementation class, we can delete at any time, reduce the historical burden!

Package-level private implementation classes:

Multiple configuration input methods

Each jar package basically has its own configuration, and if these configurations are initialized, there will be a lot of attention. The most unreliable thing I have encountered is to require that the absolute path of the file must be provided, and even some only support the default absolute path and not custom!

Because I come across a lot of such weird packages, I will pay special attention when writing jar packages.

To sum up, we should provide the following three initialization methods for configuration:

File path, which must support the classpath: prefix, which represents loading from the classpath

InputStream, which supports reading from a stream

A custom Config class that contains all the configuration items you need and sets the default values

The third of these, the custom Config class, is the most recommended practice.

Taking the client above as an example, we can provide three constructors:

RocketMqEventClient (Config config) {this.config = config; client = new RocketMqClient ();} RocketMqEventClient (InputStream in) {init (in);} RocketMqEventClient (String filePath) {if (filePath = = null | | filePath.trim () .isEmpty ()) {throw new IllegalArgumentException ("File path cannot be empty") } if (filePath.startsWith (CLASSPATH)) {/ / load String path = filePath.replaceFirst (CLASSPATH, ") from the classpath; try (InputStream in = RocketMqEventClient.class.getClassLoader (). GetResourceAsStream (path)) {init (in);} catch (IOException e) {throw new IllegalArgumentException (" profile read failed: "+ filePath, e) }} else {/ / Direct read file path try (InputStream in = new FileInputStream (filePath)) {init (in);} catch (IOException e) {throw new IllegalArgumentException ("configuration file read failed:" + filePath, e);}} private void init (InputStream in) {config = new Config (in); client = new RocketMqClient ();}

These parameter types are then supported in the factory class:

/ * * event client factory * * @ author huangxuyang * @ since 2019-06-29 * / public class EventClientFactory {/ * create default event client * * @ param config configuration items * @ return default event client * / public static EventClient createClient (Config config) {return new RocketMqEventClient (config) } / * create default event client * * @ param in profile input stream * @ return default event client * / public static EventClient createClient (InputStream in) {return new RocketMqEventClient (in) } / * create default event client * * @ param filePath profile path, support classpath: prefix * @ return default event client * / public static EventClient createClient (String filePath) {return new RocketMqEventClient (filePath);}} support Spring @ Enable mode

As SpringBoot becomes more and more popular, the configuration of starter makes us feel that it is so convenient to integrate third-party dependencies. It would be cool if our jar package also supports starter. But I generally consider that many projects are not built using SpringBoot, but traditional Spring projects. In order to take into account these projects, we can actually use the @ EnableXxx mode, which is just an extra annotation with starter. We just need to do this:

Introduce spring-context dependency, pay attention to add provided

Use @ Value annotations on the fields of our custom Config class to automatically inject configuration items from the Spring context

Add XxxConfiguration class to register Bean

Add the @ EnableXxx annotation and import the newly defined configuration class @ Import ({Config.class, XxxConfiguration.class})

Taking the previous event client as an example, you can do this:

Introduction of spring-context

Org.springframework spring-context 5.1.8.RELEASE provided

Add @ Value annotations to the fields of the Config configuration class

@ lombok.Datapublic class Config {@ Value ("${event.mq.namesrvaddr}") private String rocketMqNameSrvAddr; @ Value ("${event.mq.clientName}") private String rocketMqClientName; @ Value ("${event.mq.subject}") private String subject; @ Value ("${event.mq.pool.maxSize}") private int maxPoolSize;}

Add an EventClientConfiguration class

/ * event client auto-assembly configuration class * * @ author dadiyang * @ since 2019-06-29 * / @ Configurationpublic class EventClientConfiguration {@ Bean public EventClient eventClient (Config config) {return EventClientFactory.createClient (config);}}

Add @ EnableEventClient comment

/ * * enable event client module * * @ author dadiyang * @ since 2019-06-29 * / @ Documented @ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Import ({Config.class, EventClientConfiguration.class}) public @ interface EnableEventClient {}

With this annotation, if users integrate with Spring, they only need to mark @ EnableEventClient on the class with @ Configuration annotation, and then @ Autowired can be automatically injected into our EventClient class!

If the team is all using SpringBoot for development, you can also provide a starter.

At this point, the study of "case study of jar package in java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report