Get the App
SLTechnology News&Howtos  ›  Development  › 

How to call the methods of Dao layer and Service layer in Spring main method

Shulou Source: shulou.com Published: 2022-06-02 08:26:57 10月31日 Update

This article introduces the knowledge of "how to call Dao layer and Service layer methods in Spring main method". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The Spring main method calls the methods of the Dao layer and Service layer

In a web environment, database connections such as dao in serviceImpl are created by the container when it is started and will not report an error.

But in main, there is no such environment, so you need to get the environment:

ApplicationContext ctx = new FileSystemXmlApplicationContext ("src/applicationContext.xml"); PianoServiceImpl pianoService = (PianoServiceImpl) ctx.getBean ("pianoServiceImpl"); / / then call the method return pianoService.getPriceByBrand (brand); how to access the service layer or Dao layer directly in the ordinary class

Recently encountered a problem, how to access the dao layer and service layer methods in the tool class, because I may have a weak foundation, at first did not think of the error point, and then debug found that my service or dao are empty.

Because the service layer is usually called in controller, scan injection is configured, and spring will automatically inject the dependent service layer according to the configuration.

But because the utility class we write does not belong to the controller layer, when the written interface needs to call the service layer, it is often NULL.

Let me share my solution directly:

The first scheme

Write a method implements ApplicationContextAware interface

And then in your tool class

ApplicationContext appCtx = SpringContextUtil.getApplicationContext (); StatusMapper statusMapper = (StatusMapper) appCtx.getBean (StatusMapper.class)

Just call it directly this way.

The second option

I saw it on the Internet. It hasn't been verified.

1. Add the @ Component annotation to this utility class

two。 Set the required service class to the static property, and directly set the service layer to the tool class's own property through the method.

This is the end of "how to call Dao layer and Service layer methods in Spring main methods". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Methods tools services solutions environment content properties interfaces are in more knowledge configuration practical ordinary weak learned and then dilemma actual container Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Huawei macOS MySQL Apple