PHP-based engineer touched Java's Spring Boot

Preface

I usually touch PHP and javascript mainly, but I had the opportunity to touch Spring Boot of Java, so I will write what I learned at that time and what I found useful.

environment

java version 1.8.0_92 Spring Boot v1.5.8 Maven

IDE In PHP, I used vim in my previous job and recently phpstrom, but Java's Spring Boot development environment uses eclipse or STS (Spring Tool Suite). It seems that STS is also based on eclipse, and when I tried using it this time, I got the same impression as eclipse.

Annotation

Perhaps the biggest feature of Spring is this annotation. I think that many people who have used phpunit etc. have used @Test or @dataProvider, but such annotations can be used everywhere. Here are just two annotations that you probably used the most.

Dependency Injection: It's called Dependency Injection. If you declare @Autowired in the class, you can use the object even though you have not created the object with new.

@Autowired
private TestClass testClass;

You can define SQL and execute it when the set method is called. Also, at that time, various ways of writing spring are available.

@Repository
public interface TableDao {
    @Query("SELECT s FROM table s ORDER BY id DESC")
    List<Table> findAllRecord();

    @Query("FROM Table WHERE id = ?1)
    List<Table> findById(int id);
}

Use of the library

If you want to use a library other than standard functions in PHP, I think that composer is the mainstream now, but in Java development using Maven, set the library to be used in dependency.

You can find the libraries available in maven from the Maven Repository. https://mvnrepository.com/

Specifically, when you create a project, a file called pom.xml is created in it, so describe the repository you want to use there as follows. However, if you are using the IDE, it is convenient because the following settings will be described without permission just by entering the parameters on the setting screen without writing the code yourself.

<dependencies>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-csv</artifactId>
		<version>1.5</version>
	</dependency>
</dependencies>

Application settings

In Spring boot, the application settings are described in the file src / main / resources / application.properties. For example:

# setting of database
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=1234

# Redis
# Specify the DNS URI of your Redis cache.
spring.redis.host=localhost

#### application properties ####
# application log dir
path.log-dir=/Users/user/tmp/logs

By writing like this, you can easily change various settings such as redis and database, Also, for example, in code

public class Application {
    @Value("${path.log-dir}")
    private String logDir;

    public static void main(String[] args) {
        System.Out.Println(logDir);
    }
}

You can also use the settings written in properties like this.

MVC framework

In PHP, it's called Model, View, Controller, but in Spring, it's called Service, View, Controller. It seems that business logic is described in Service, but I think that it is almost the same as Model. I created a Thread class under Service and called it from Service, but it seems to be quite common.

Multithread

I had a lot of trouble implementing it at first because of a concept that PHP doesn't have. In Java, multiple threads can be run at the same time, so you need to think about the code properly, such as making it thread-safe so as not to affect other threads at that time. There is no problem if it is implemented with a single thread, but if it is implemented with Java, I would like to make it multithreaded and maximize the performance.

A lot of code has to be written

This is what I found inconvenient when writing Java code. For example, if you want to execute a command on the command line in php,

if ( !exec('command 2>&1',$array)) {
    var_dump($array);
}

If you write like this, you're done. If it's Java,

String executeCmd = new String[] { "bash", "-c", command };
Process p = new ProcessBuilder(executeCmd).start();
p.waitFor();
BufferedReader buffRead = new BufferedReader(new InputStreamReader(p.getErrorStream()));

while ((strLine = buffRead.readLine()) != null) {
    System.Out.Println(strLine);
}
buffRead.close();

It becomes like. (There may be a simpler way to write it in Java, but this was the way I looked it up) I think it's because I'm not used to Java, but as the amount of code increases when writing in Java everywhere, the research time to investigate how to write a program has increased significantly.

Also, Java requires you to write try {...} catch () {...} everywhere. Although the IDE complements it, I found it quite inconvenient compared to PHP.

The mold is strict and spicy. There is no convenient type like PHP array.

Unlike PHP, Java is quite strict in type conversion. Recently, even in PHP, writing types with declarations such as functions has increased, but it was quite cramped for me as a PHP person to always write types.

In particular, it was quite painful that I couldn't handle hashes and arrays like PHP's array conveniently, and I had to bother to create a class for the return value. For example

public String getClient(){
   return "name";
}

String client = getClient();

If you want to return the id of client in addition to name in the function, PHP,

public function getClient(){
    return array("name", 1);
}

list ($name, $id) = getClient();

It's easy to change, but if you write it properly in Java,

class Client {
   private int id;
   private String name;

   public Client(int id, String name) {
       this.id = id;
       this.name = name;
   }
}

public Client getClient() {
   return new Client("name", 1);
}

Client client = getClient();

You need to create a class of return values like this. Of course, you can make it Object [] or return it as String [] and recast it to int, but when writing in Java, it is common to make the result properly in the class. Then I had to write a lot of code compared to php, which was a lot of work for me.

It's convenient because you only have to choose how to deal with the error.

phpstorm is also useful because it suggests countermeasures for errors, but Java has only the original static language, so it is quite kind to deal with errors. If there is an error, just click the error on the IDE → select a solution and most of the errors will be resolved. Even if I haven't developed it in Java in earnest, I rarely stumble on errors, and I thought this part was really wonderful.

Conclusion

It may all be that I'm new to Java, but Java is much slower to develop than PHP. After all, I like PHP because it is comfortable. However, since it is not possible to implement it roughly like PHP with Java, I think it is certain that even if the quality of the engineer is low, code that is more maintainable than PHP can be applied.

Also, for some reason spring has few Japanese documents, and it was faster to look it up in English to do anything, so if you are accustomed to PHP, which has abundant documents in Japanese, such a place may be painful. not.

Recommended Posts

PHP-based engineer touched Java's Spring Boot
A memo that touched Spring Boot
Challenge Spring Boot
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
Spring boot memo writing (1)
SPRING BOOT learning record 02
Spring Boot2 cheat sheet
Spring Boot exception handling
Spring Boot Servlet mapping
Spring boot development-development environment-
Spring Boot learning procedure
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Spring Boot on Microsoft Azure
Spring Boot tutorial task schedule
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Hello World with Spring Boot!
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Spring Boot DB related tips
Hello World with Spring Boot
Set cookies with Spring Boot
[Spring Boot] Easy paging recipe
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Major changes in Spring Boot 1.5
Add module with Spring Boot
Getting Started with Spring Boot
NoHttpResponseException in Spring Boot + WireMock
[Spring Boot] Send an email
Spring Boot performance related settings
Introduction to Spring Boot Part 1
Spring Boot External setting priority
Try using Spring Boot Security
[Java] [Spring] Spring Boot 1.4-> 1.2 Downgrade Note
Try Spring Boot on Mac
Create microservices with Spring Boot
Spring Boot DB connection pool