search
HomeJavajavaTutorialHow SpringBoot calls the service layer in a custom class

Background:

A TCP server was built to connect to smart devices, and then the key information such as positioning and other information sent by the device in real time needs to be stored in the database.

In order to consider the possibility of providing a rest interface to the outside world in the future, the TCP server is integrated into the SpringBoot framework. Of course, it is also to use the mybatis framework to achieve data access as quickly as possible, and then solve various problems such as how to start, how to log out, etc. The problem is that when processing TCP server messages, you need to write to the database, directly call the DAO layer, and compile and report an error.

Instead of calling the Service layer, it compiles normally and runs to the calling place. A null pointer exception is reported. The exception location is traced and the service is found to be empty. In other words, the service layer injected through @Autowired through the previous controller layer fails.

Solution:

1. Upload the code

@Component
public class ServerHandler extends IoHandlerAdapter {
    @Autowired
    protected HealthDataService healthDataService;
    private static ServerHandler  serverHandler ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {  
        serverHandler = this;  
        serverHandler.healthDataService = this.healthDataService;        
        // 初使化时将已静态化的testService实例化
    }  
    //测试调用
    public void test(){
        serverHandler .healthDataService.;
    }

2. Description:

Annotate the class that needs to call Spring's Service layer with @Component as Component loading;

Also obtain the Bean object of the Service layer through @Autowired;

Declare a static variable for the class to facilitate the next step of storing the bean object;

Highlight: Pass Annotate @PostConstruct to initialize the static object and its static member variable healthDataService during initialization. The principle is to get the service layer bean object and store it statically to prevent it from being released.

Those pitfalls:

When I first started calling, I always thought it was very simple. In the past, springmvc wrote a configuration and marked the object as a bean and you could call it at will. The beans of the Spring IOC container are available, but this is SpringBoot, so there is probably still a difference. I tried the first three pages of help from Baidu, but basically no success. Including:

1) Declare the tool class as a spring component, such as @controller @compent, etc., and add the package where the tool class is located in the spring automatic scan package setting; invalid

2) new a service; invalid;

Transaction processing of multiple services calling each other in springboot

I want to call method B of another service in method A of one service, both method A and method B There is a database insertion operation, and the @Transaction annotation is also added, but when an exception is thrown in method B, the insert statement in A can still be executed successfully.

The annotation configuration is as follows:

@Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED)

I was puzzled. After searching for relevant information, I found that the problem still lies in the configuration of the @Transaction annotation, which requires configuring exception rollback.

@Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)

In this way, when an exception is thrown in method B, the operation in A will also be rolled back, and the transaction will play a controlling role.

The above is the detailed content of How SpringBoot calls the service layer in a custom class. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor