[Plugin Collection] Will you use these when you write code?

Preface

Eclipse/IDEA provides an extensible plug-in development system, which allows them to implement various functions on the running system. In our daily development, reasonable use of some plug-ins can greatly improve our development efficiency. The following is just a summary of my daily work and a compilation of commonly used plug-ins, I hope to help everyone~

One, Lombok

Lombok is a tool that can help us simplify and eliminate some bloated JAVA code through simple annotations. By using the corresponding annotations, the corresponding method can be generated when the code is compiled, so that our code looks more neat and concise. For example, a series of methods such as getter and setter in the entity class.

1.Lombok installation

1.1 IDEA install Lombok

1. Online installation: Menu File->Settings->Plugins->Browse
repositories...->Search lombok->get the result Lombok plugin, download (install) and restart it.
2. Offline installation: first download lombok.jar, download URL: lombok.jar, then menu File->Settings->Plugins->Install
plug from disk-> select the lombok.jar you downloaded, then apply->OK, Restart is ok.

1.2 Eclipse install Lombok

(1) First download lombok.jar, and open the installation directory of myeclipse or eclipse, and find the file directory where myeclipse.ini/eclipse.ini is located.

(2) Open myeclipse.ini/eclipse.ini and add at the end of the configuration

-javaagent:lombok.jar

-Xbootclasspath/a:lombok.jar

(3) Restart myeclipse or eclipse after saving.

2. Use lombok in Java maven project, add Lombok dependency

<dependency>

          <groupId>org.projectlombok</groupId>

          <artifactId>lombok</artifactId>

          <version>1.16.18</version>

          <scope>provided</scope>

 </dependency>	

Lombok's scope=provided means that it only takes effect during the compilation phase and does not need to be included in the package. This is the fact that Lombok correctly compiles Java files with Lombok annotations into complete Class files during compilation.

3. Use of Lombok annotations

@Getter/@Setter: On the function class, generate the getter/setter methods of all member variables; when acting on the member variable, generate the getter/setter methods of the member variable. You can set access permissions and whether lazy loading, etc.

@ToString: Act on the class, override the default toString() method, display certain fields through the of attribute, and exclude certain fields through the exclude attribute.

@EqualsAndHashCode: Acting on the class, overriding the default equals and hashCode

@NonNull: Mainly used in member variables and parameters. The identifier cannot be null, otherwise a null pointer exception will be thrown.

@NoArgsConstructor, @RequiredArgsConstructor,
@AllArgsConstructor: Act on the class to generate constructors. There are staticName, access and other attributes.

Once the staticName attribute is set, an instance will be generated using a static method, and the access attribute can limit access permissions.

@NoArgsConstructor: Generate no-argument constructor;

@RequiredArgsConstructor: A constructor that generates member variables with final and @NonNull annotations;

@AllArgsConstructor: Generate full parameter constructor

@Data: Act on the class, is a collection of the following annotations: @ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor

@Builder: Acting on the class, turning the class into a builder mode

@Log: Act on the class to generate log variables. There are different annotations for different log implementation products:

package com.kaplan.pojo;

import lombok.*;

import lombok.extern.log4j.Log4j;
//默认生成的方法是 public 的,如果要修改方法修饰符可以设置 AccessLevel 的值
@ToString(of = {
    
    "name","age"},exclude = {
    
    "age"})
@Getter(access = AccessLevel.PROTECTED)
@Setter(access = AccessLevel.PROTECTED)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class TestDemo {
    
    

@NonNull
private String name;
private int age ;
private String email;
private String address; 

@Getter
@Setter 
private String dob;
}

The above is just an introduction to the common annotations of the POJO class. The annotations of Lombok include but are not limited to this. There are many annotations that are not introduced here. If you are interested, you can learn privately.

Two, FindBugs

As the project gets bigger and bigger, the time is getting longer and longer, and the code review work is a huge burden. Our daily JAVA code is checked by FindBugs before submitting to SVN. So what exactly is FindBugs? FindBugs is a static analysis tool that examines classes or JAR files and compares bytecode with a set of defect patterns to find problems. Findbugs comes with detectors, including more than 60 types of Bad
practice, more than 80 types of Correctness, 1 type of Internationalization, 12 types of Malicious code
vulnerability, 27 types of Multithreaded
correctness, 23 types of Performance, and 43 types of Dodgy. There are personalized settings: we can configure the inspection rules ourselves (what to do and what not to do), or we can implement our own unique verification rules (user-defined specific bug modes need to inherit its interface , Write your own verification class, which is an advanced technique). FindBugs checks java bytecode, which is *.class file.

1. The necessity of code inspection
In other words, why do we need code inspection? Although there is no grammatical error in a certain code writing method, there may be errors, such as potential bugs such as thread deadlock, etc., these are the error list to be checked, static checking can be operated:

1.1 Code walkthrough: (The method adopted by the previous company)  
programmers can extract code for walkthrough at a certain time interval.

According to the summary report during the walkthrough, these experiences will be compiled into a list as the basis for the next code walkthrough.

The characteristics of this method are manual, multi-person discussion, and simple operation, but the efficiency is relatively low.
2.2 Code scanning

Use software to scan our code to find potential problems. There are many commercial tools available for scanning, such as Parasoft JTest, Software
Analyzer, pclint, Findbugs and other tools. Software scanning is characterized by machine scanning and high efficiency, but it is not flexible enough and not conducive to expansion.

2. FindBugs installation

2.1 IDEA install FindBugs

(1) Online installation: Menu File->Settings->Plugins->Browse
repositories ...-> Search FindBugs in the search box-> Get the result FindBugs-IDEA, download (install) and restart it.

(2) Offline installation: first download the FindBugs compressed package, download URL: FindBugs compressed package, then menu File->Settings->Plugins->Install
plug from disk-> select the FindBugs compressed package you downloaded (because it contains more jar packages) Many), then apply->OK, restart is ok.

2.2 eclipse install FindBugs

(1)在线安装:
eclipse:Help->Install New
Software->Add->Name:findbugs,Location:http://findbugs.cs.umd.edu/eclipse

Then click OK, select FindBugs, then you can go to Finish all the way, restart eclipse, select any item, right click the mouse, if findbugs appears in the pop-up box, it means the installation is successful or open eclipse->window->Preferences, search for keywords findbugs, if the configuration item can be found, then the installation is successful.

(2) Offline installation:

First you need to download the compressed package of FindBugs you apply: Download URL: FindBugs for eclipse, then open the eclipse installation directory, find dropins or plugins (any one), put the compressed package into this directory, and then start eclipse , Select any item, right click the mouse, if findbugs appears in the pop-up box, the installation is successful or open eclipse->window->Preferences, search for the keyword findbugs, if you can find the configuration item, then the installation is successful.

(3) If there is no Bug
Explorer after clicking Find Bugs->Find Bugs , then Window->ShowView->Other->FindBugs->Bug Explorer. The bugs found have 3 colors. The
black bug symbol is classified, the red bug indicates that the code must be modified after a serious bug is found, and the orange bug indicates a potential warning bug.

3. Use FindBugs in IDEA

Select the project, package, class, right click the mouse, select FindBugs, Analyze Selected File(s) single file, Analyze Package(s) Files package, Analyze Module Files entire module, Analyze Project Files entire project

4. Some common mistakes: the following are copied and modified by others, for the convenience of learning by yourself in the future, please forgive me

4.1 Bad practice is mainly some bad habits in the code.
Class names should start with an upper case letter are not used in accordance with the Java specification. Class names should start with an upper case letter.
Method names should start with a lower case letter. Method names should start with a lower case letter. beginning with a letter
field names should start with a lower case letter lowercase letter name field
equals () method does not check for null argument equals () method should examine the non-empty
class defines equals () and uses Object.hashCode () covered a class The equals method is written, the hashCode method is not overwritten, and the hashCode method of the Object object is used.
Method ignores exceptional return value.
Equals method should not assume anything about the type of its argument equals(Object o) The type of parameter o makes any assumptions. Compare this object with the specified object. The result is true if and only if the parameter is not null and is an object representing the same type as this object.
Comparison of String objects using == or != Use == or! = To compare objects of type String
Method might ignore exception Method might ignore exception
Method invokes System.exit() Call System.exit(…) statement in the method, consider using RuntimeException instead of
Method ignores result of InputStream.read() InputStream.read method ignores multiple characters returned, if the result is not checked The situation where the user requests to read a few characters cannot be handled correctly.

4.2 Dodgy code Bad code (usually the code is not written according to the Java specification, or the statement is incomplete, type conversion, redundant statement, judgment)
Switch statement found where default case is missing Switch has no case statement that is executed by default
Switch statement found where one case falls through to the next case Switch statement executes a branch after executing the next branch. Usually case is followed by a break or return statement to jump out.
Dead store to local variable This instruction assigns a value to a local variable, but there is no use to it in the following. Usually, this indicates an error because the value has never been used.
Write to static field from instance method In the
Redundant nullcheck of value known to be non-null method, the non-null value is judged as null in the Write to static field from instance method .
Method uses the same code for two branches This method uses the same code for two branches. Check to make sure this is not a coding error.
Exception is caught when Exception is not thrown. The exception is caught when Exception is not thrown in the try/catch block, but the exception is not thrown in the try statement and RuntimeException is not explicitly caught
Integral division result cast to double or The float integer division is forced to be converted to double or float type.
Possible null pointer dereference due to return value of called method The return value of the called method is re-assigned without checking whether it is null, so a null pointer exception may occur.
Useless object created Object created and not used
Unread public/protected field Unused field

4.3 Internationalization
Consider using Locale parameterized version of invoked method on code internationalization-related aspects.
Use the platform's default encoding format to convert the string to upper and lower case, which may lead to improper conversion of international characters. Use the following method to convert characters

4.4 Performance Regarding code performance related aspects (mostly useless attributes are declared)
Boxing/unboxing to parse a primitive type conversion, such as string conversion to int, should use Integer.parseInt("") instead of Integer.valueOf("")
Method concatenates string using + in aloop
Each time the string + connection in the loop, a new string object will be generated. In Java, the cost of creating a new object is very expensive, especially in the loop statement, the
solution is inefficient : Use StringBuffer or StringBuilder to reuse objects.
Private method is never called
Explicit garbage collection is not called ; extremely dubious except in benchmarking code
explicitly calls garbage collection naming in the code, which does not work. In the past, someone called the garbage collection method in the close operation or finalize method, which caused a lot of performance waste. Such large-scale recycling of objects will cause the processor to run slowly.
Unread field:should this field be static? Unread field
should be a static inner class should be a static inner class

4.5 Experimental
Method may fail to clean up stream or resource on checked exception
This method may not be able to clean up (close, dispose) a stream, database object, or other resource. A clear cleaning action is required.
Solution: The closing of the stream is written in finally inside

4.6 Malicious code vulnerability Regarding malicious code vulnerability (mainly some attributes, it is recommended to change to private and provide get, set methods for it)
May expose internal representation by incorporating reference to mutable object
This code stores the external mutable object reference to The internal representation of the object. If the instance is accessed by untrusted code and unchecked changes endanger the security of the object and important attributes. Storing a copy of an object is a better way in many cases.
Field isn't final but should be final
Field isn't final and can't be protected from malicious code Before this field should be final
Field should be package protected
A static field can be malicious code or other Package access modification. You can declare this type of field as final to prevent this error.

4.7 Multithreaded correctness
Static DateFormat DateFormat related to code correctness is inherently unsafe in multiple threads. If an instance of DateFormat is shared in the thread range without using a synchronized method, some strange behaviors will occur in the application. .
Call to static DateFormat DateFormats is not safe to use multi-threaded skills, improvement method: need to create multiple instances or thread synchronization

4.8 Correctness
Nullcheck of value previously dereferenced related to the correctness of the code This code previously abandoned the null value check. Solution Perform a null check.
Possible null pointer dereference may be null.
Null pointer dereference object has not been reassigned after being assigned a null value.
Possible null pointer dereference in method on exception path. In the method of abnormal null value processing branch call, there may be object dereference Operation
value is null and guaranteed to be dereferenced on exception path exception branch, there is a method to refer to a null object, which causes a null pointer exception.
The Self comparison of value with itself method performs a comparison operation on a local variable itself and can explain errors or logic errors. Please make sure you are more correct.

An apparent infinite recursive loop will cause a stack overflow.

Three, PageHelpher

When using java Spring to develop, Mybatis can be regarded as a powerful tool for database operations. But when dealing with paging, we are accustomed to using limit for paging, and the cost is relatively high. PageHelper physical paging ( official website click me ) is more convenient for single table paging or overall result set paging.

1. Introduce the Maven dependency of PageHelper

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

2. Configure the applicationContext.xml file
to add a paging interceptor attribute to the bean of spring's sqlsessionfactory

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="plugins">
		<array>
			<bean class="com.github.pagehelper.PageInterceptor">
				<property name="properties">
					<value>
						<!-- 这里设定你的数据库类型 -->
						helperDialect = mysql
					</value>
				</property>
			</bean>
		</array>
	</property>
</bean>

3. Call PageHelper method

In the service method, call the static method startPage of PageHelper (note that this method must be called before the actual query), pass in the page number pageNum to be queried and the number of items displayed per page pageSize, and return the PageInfo object provided by the PageHelper plug-in. You can automatically complete the physical paging of the database without manually adding a limit clause to the sql statement

@Override
public PageInfo<Student> testPage(Integer pageNum, Integer pageSize) {
    
    
	PageHelper.startPage(pageNum,pageSize);
	List<Student> studentList = studentMapper.selectAll();

	PageInfo pageInfo = new PageInfo(studentList);
	return pageInfo;
}

4. The efficiency problem caused by the large amount of data PageHelper

In the development process, we inevitably use paging. Normally, the PageHelper plug-in is very convenient for paging, but when the project data volume is large, the query speed of the paging plug-in will be slow. . Later comparison found that SQL is inefficient due to the offset of limit

The SQL originally written was like this:

select * from school where age >= 18;

The final execution is like this:

select * from (select * from school where age >= 18)where limit 100,10;

The official explanation of supportMethodsArguments is as follows:

  1. supportMethodsArguments: Support to pass paging parameters through Mapper interface parameters, the default value is false, the paging plug-in will automatically select the value from the parameter value of the query method according to the field configured by params above, and automatically paging when it finds a suitable value. For the usage method, please refer to ArgumentsMapTest and ArgumentsObjTest in the com.github.pagehelper.test.basic package in the test code.
  2. params: In order to support the startPage (Object params) method, this parameter is added to configure the parameter mapping, which is used to obtain the value from the object according to the attribute name. You can configure
    pageNum, pageSize, count, pageSizeZero, reasonable, and use the default value if the mapping is not configured , The default value is pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero.

What does that mean? When using the pageHelper plug-in, as long as the parameters passed to the Mapper include pageNum and pageSize, it will automatically append countSql for paging processing. **In other words, it will intercept the sql statement we write, repackage it by itself, and add limit at the back. **This is of course no problem when the amount of data is small, but once the amount of data is too large, the offset of limti will inevitably increase when paging to the subsequent data. Inevitably, the query time will be a geometric multiple increase.

Solution

Scenario 1: Modify the configuration

Checked the pageHelper configuration and found that the configuration is as follows

pagehelper:
	 helperDialect: mysql
	 reasonable: true
	 supportMethodsArguments: true  ###注意这一条

The easiest way is to set the supportMethodsArguments attribute to false, the second way is to modify the interface

public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {
    
     
	return startPage(pageNum, pageSize, count, null, null); 
}

Cancel the previous comment and rewrite it as

PageHelper.startPage(query.getPageNum(),query.getPageSize(),false);

Scheme 2: Modify the count statement

The query API found that PageHelper actually supports automatic detection of count statements.

Add handwritten count query support.
Add countSuffix count query suffix configuration parameter. This parameter is configured for PageInterceptor and the default value is _COUNT. The paging plug-in will first find the handwritten paging query through the msId + countSuffix of the current query. If it exists, use the handwritten count query, if it does not exist, still use the previous method to automatically create the count query.

What does that mean? For example, your paging query interface is named getAllUser, as long as you name the count statement you wrote getAllUser_COUNT, PageHelper will use the count statement written by ourselves, and will no longer be automatically generated.

 <select id="getAllUser_COUNT" resultType="Long">

 select max(id) from student
 </select>

Scenario 3: Modify the table engine

Modify the table engine directly. If the default is InnoDB, because the engine does not save the specific number of rows in the table, the statistics will be basically more than 1 second after the data volume reaches one million;

Modified to MyISAM; but in the case of paging query, the record query after 1 million will be very slow;

Four, Regex Util

Regex Util is a regular expression testing plug-in, which can highlight regular expression syntax, bracket matching, and error detection. Be able to remind the detailed description of the regular expression function.

Official website: http://myregexp.com/eclipsePlugin.html
Eclipse online installation URL: http://regexutil.sourceforge.net/update/

The main plug-ins currently used by the host are these, and will be added in the future. Welcome everyone to ask questions to learn from each other~

Guess you like

Origin blog.csdn.net/weixin_42777004/article/details/108646543