NAZEHA
NAZEHA

Reputation: 455

Spring mvc: Best paractices for software architecture

I develop rest Web services using spring mvc.

I know that the application should contains 3 layers:

persistence layer: classes annotated with @Repository

service layer: classes annotated with @Service

controller layer: classes annotated with @Controller

For my case, Data are loaded first from a restful ws (a backend) then stored into database and after a laps time, my project reload it from the rest ws (backend) to refresh the data and use it to offer some services.

So the java classes which call backend ws should be annotated with @Service ? and then called directly from controller? How to arrange the project architecture in this case? Is it the same architecture as those using data from database ?

thanks

Upvotes: 0

Views: 431

Answers (1)

andreas
andreas

Reputation: 985

From my understanding your database is some kind of cache for the webservice data right?

So I would implement some @Service bean(s) that is/are responsible to retrieving data from the WS, lets call it "WSAccessBean".

Now two approaches come to my mind:

  1. Eager loading: Your Spring servlet will use scheduled-tasks to periodically call the WSAccessBean and store the retrieved data in the database. You controller beans will use @Repository beans as usual to access this data.
  2. Lazy loading: You implement another @Service bean(s) that is a facade for the data access, lets call it "DataAccessBean". This one will use both: @Repository beans to check if up-to-date data is in our local database and if not it will use the WSAccessBean to first retrieve the data and then return it from the database to the caller.

edit after comment:

So if your data needs to be loaded on demand the following snippet would show the basic architecture using a "Book" POJO as example:

@Service
public class BookWebservice {
    // Load books from remote webservice
    List<Book> retrieveBooks();
}

@Repository
public class BookDAO {
    List<Book> getBooks();
    void storeBooks(List<Book> books);
    boolean uptodate();
}

@Service
public class BookService {

    @Autowired
    BookDAO bookDAO;

    @Autowired
    BookWebservice bookWebservice;

    // Checks if local data is up-to-date. If not load via Webservice and store in the local DB, then return content from DB
    List<Book> getBooks() {

        if (!bookDAO.uptodate()) {
            bookDAO.storeBooks(bookWebservice.retrieveBooks());
        }
        return bookDAO.getBooks();
    }
}

@Controller
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping("/books")
    public List<Book> books() {
        return bookService.getBooks();
    }
}

Upvotes: 1

Related Questions