Проектиране на модели в пролетната рамка

1. Въведение

Моделите на проектиране са съществена част от разработването на софтуер. Тези решения не само решават повтарящи се проблеми, но също така помагат на разработчиците да разберат дизайна на рамката, като разпознават често срещаните модели.

В този урок ще разгледаме четири от най-често срещаните дизайнерски модели, използвани в Spring Framework:

  1. Единичен модел
  2. Модел на фабричен метод
  3. Прокси модел
  4. Шаблон шаблон

Ще разгледаме също как Spring използва тези модели, за да намали тежестта за разработчиците и да помогне на потребителите бързо да изпълняват досадни задачи.

2. Единичен модел

Единичният модел е механизъм, който осигурява само един екземпляр на обект за приложение . Този модел може да бъде полезен при управление на споделени ресурси или предоставяне на междусекторни услуги, като регистриране.

2.1. Сингълтън боб

Като цяло сингълтънът е глобално уникален за приложение, но през пролетта това ограничение е облекчено. Вместо това Spring ограничава единичен елемент до един обект за Spring IoC контейнер . На практика това означава, че Spring ще създаде само по един компонент за всеки тип за контекст на приложение.

Подходът на Spring се различава от строгото определение на сингълтон, тъй като приложението може да има повече от един Spring контейнер. Следователно, множество обекти от един и същи клас могат да съществуват в едно приложение, ако имаме множество контейнери.

По подразбиране Spring създава всички зърна като единични.

2.2. Автоматично свързани кабели

Например, можем да създадем два контролера в рамките на един контекст на приложение и да инжектираме боб от същия тип във всеки.

Първо, ние създаваме BookRepository, който управлява нашите обекти на домейна на Book .

След това създаваме LibraryController , който използва BookRepository, за да върне броя на книгите в библиотеката:

@RestController public class LibraryController { @Autowired private BookRepository repository; @GetMapping("/count") public Long findCount() { System.out.println(repository); return repository.count(); } }

И накрая, ние създаваме BookController , който се фокусира върху специфични за книгата действия, като например намиране на книга по нейния идентификатор:

@RestController public class BookController { @Autowired private BookRepository repository; @GetMapping("/book/{id}") public Book findById(@PathVariable long id) { System.out.println(repository); return repository.findById(id).get(); } }

След това стартираме това приложение и изпълняваме GET on / count и / book / 1:

curl -X GET //localhost:8080/count curl -X GET //localhost:8080/book/1

В изхода на приложението виждаме, че и двата обекта BookRepository имат един и същ идентификатор на обект:

[email protected] [email protected]

На BookRepository идентификатори обект в LibraryController и BookController са същите, доказвайки, че Spring инжектира същото боб в двете контролери.

Можем да създадем отделни екземпляри на зърното на BookRepository, като променим обхвата на зърната от единичен на прототип, като използваме анотацията @ Scope (ConfigurableBeanFactory.SCOPE_PROTOTYPE) .

По този начин инструктирате Spring да създава отделни обекти за всеки от зърната на BookRepository, който създава. Следователно, ако отново проверим идентификатора на обекта на BookRepository във всеки от нашите контролери, ще видим, че те вече не са еднакви.

3. Образец на фабричен метод

Шаблонът на фабричния метод включва фабричен клас с абстрактен метод за създаване на желания обект.

Често искаме да създаваме различни обекти въз основа на определен контекст.

Например, нашето приложение може да изисква обект на превозно средство. В морска среда искаме да създадем лодки, но в космическа среда искаме да създадем самолети:

За да постигнем това, можем да създадем фабрична реализация за всеки желан обект и да върнем желания обект от конкретния фабричен метод.

3.1. Контекст на приложението

Spring използва тази техника в основата на своята рамка Dependency Injection (DI).

Основно пролетта третира контейнера за боб като фабрика, която произвежда боб.

По този начин Spring определя интерфейса BeanFactory като абстракция на контейнер за боб:

public interface BeanFactory { getBean(Class requiredType); getBean(Class requiredType, Object... args); getBean(String name); // ... ]

Всеки от методите getBean се счита за фабричен метод , който връща боб, отговарящ на критериите, предоставени на метода, като типа и името на боб.

След това Spring разширява BeanFactory с интерфейса ApplicationContext , който въвежда допълнителна конфигурация на приложението. Spring използва тази конфигурация за стартиране на контейнер за боб, базиран на някаква външна конфигурация, като XML файл или Java анотации.

Използвайки реализациите на класа ApplicationContext като AnnotationConfigApplicationContext , можем да създадем боб чрез различните фабрични методи, наследени от интерфейса BeanFactory .

Първо, ние създаваме проста конфигурация на приложението:

@Configuration @ComponentScan(basePackageClasses = ApplicationConfig.class) public class ApplicationConfig { }

След това създаваме прост клас, Foo , който не приема аргументи на конструктора:

@Component public class Foo { }

След това създайте друг клас, Bar , който приема един аргумент на конструктора:

@Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class Bar { private String name; public Bar(String name) { this.name = name; } // Getter ... }

И накрая, ние създаваме нашите зърна чрез изпълнението на AnnotationConfigApplicationContext на ApplicationContext :

@Test public void whenGetSimpleBean_thenReturnConstructedBean() { ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); Foo foo = context.getBean(Foo.class); assertNotNull(foo); } @Test public void whenGetPrototypeBean_thenReturnConstructedBean() { String expectedName = "Some name"; ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); Bar bar = context.getBean(Bar.class, expectedName); assertNotNull(bar); assertThat(bar.getName(), is(expectedName)); }

Using the getBean factory method, we can create configured beans using just the class type and — in the case of Bar — constructor parameters.

3.2. External Configuration

This pattern is versatile because we can completely change the application's behavior based on external configuration.

If we wish to change the implementation of the autowired objects in the application, we can adjust the ApplicationContext implementation we use.

For example, we can change the AnnotationConfigApplicationContext to an XML-based configuration class, such as ClassPathXmlApplicationContext:

@Test public void givenXmlConfiguration_whenGetPrototypeBean_thenReturnConstructedBean() { String expectedName = "Some name"; ApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); // Same test as before ... }

4. Proxy Pattern

Proxies are a handy tool in our digital world, and we use them very often outside of software (such as network proxies). In code, the proxy pattern is a technique that allows one object — the proxy — to control access to another object — the subject or service.

4.1. Transactions

To create a proxy, we create an object that implements the same interface as our subject and contains a reference to the subject.

We can then use the proxy in place of the subject.

In Spring, beans are proxied to control access to the underlying bean. We see this approach when using transactions:

@Service public class BookManager { @Autowired private BookRepository repository; @Transactional public Book create(String author) { System.out.println(repository.getClass().getName()); return repository.create(author); } }

In our BookManager class, we annotate the create method with the @Transactional annotation. This annotation instructs Spring to atomically execute our create method. Without a proxy, Spring wouldn't be able to control access to our BookRepository bean and ensure its transactional consistency.

4.2. CGLib Proxies

Instead, Spring creates a proxy that wraps our BookRepository bean and instruments our bean to execute our create method atomically.

When we call our BookManager#create method, we can see the output:

com.baeldung.patterns.proxy.BookRepository$$EnhancerBySpringCGLIB$$3dc2b55c

Typically, we would expect to see a standard BookRepository object ID; instead, we see an EnhancerBySpringCGLIB object ID.

Behind the scenes, Spring has wrapped our BookRepository object inside as EnhancerBySpringCGLIB object. Spring thus controls access to our BookRepository object (ensuring transactional consistency).

Generally, Spring uses two types of proxies:

  1. CGLib Proxies – Used when proxying classes
  2. JDK Dynamic Proxies – Used when proxying interfaces

While we used transactions to expose the underlying proxies, Spring will use proxies for any scenario in which it must control access to a bean.

5. Template Method Pattern

In many frameworks, a significant portion of the code is boilerplate code.

For example, when executing a query on a database, the same series of steps must be completed:

  1. Establish a connection
  2. Execute query
  3. Perform cleanup
  4. Close the connection

These steps are an ideal scenario for the template method pattern.

5.1. Templates & Callbacks

The template method pattern is a technique that defines the steps required for some action, implementing the boilerplate steps, and leaving the customizable steps as abstract. Subclasses can then implement this abstract class and provide a concrete implementation for the missing steps.

We can create a template in the case of our database query:

public abstract DatabaseQuery { public void execute() { Connection connection = createConnection(); executeQuery(connection); closeConnection(connection); } protected Connection createConnection() { // Connect to database... } protected void closeConnection(Connection connection) { // Close connection... } protected abstract void executeQuery(Connection connection); }

Alternatively, we can provide the missing step by supplying a callback method.

A callback method is a method that allows the subject to signal to the client that some desired action has completed.

In some cases, the subject can use this callback to perform actions — such as mapping results.

For example, instead of having an executeQuery method, we can supply the execute method a query string and a callback method to handle the results.

First, we create the callback method that takes a Results object and maps it to an object of type T:

public interface ResultsMapper { public T map(Results results); }

Then we change our DatabaseQuery class to utilize this callback:

public abstract DatabaseQuery { public  T execute(String query, ResultsMapper mapper) { Connection connection = createConnection(); Results results = executeQuery(connection, query); closeConnection(connection); return mapper.map(results); ] protected Results executeQuery(Connection connection, String query) { // Perform query... } }

This callback mechanism is precisely the approach that Spring uses with the JdbcTemplate class.

5.2. JdbcTemplate

The JdbcTemplate class provides the query method, which accepts a query String and ResultSetExtractor object:

public class JdbcTemplate { public  T query(final String sql, final ResultSetExtractor rse) throws DataAccessException { // Execute query... } // Other methods... }

The ResultSetExtractor converts the ResultSet object — representing the result of the query — into a domain object of type T:

@FunctionalInterface public interface ResultSetExtractor { T extractData(ResultSet rs) throws SQLException, DataAccessException; }

Spring further reduces boilerplate code by creating more specific callback interfaces.

For example, the RowMapper interface is used to convert a single row of SQL data into a domain object of type T.

@FunctionalInterface public interface RowMapper { T mapRow(ResultSet rs, int rowNum) throws SQLException; }

To adapt the RowMapper interface to the expected ResultSetExtractor, Spring creates the RowMapperResultSetExtractor class:

public class JdbcTemplate { public  List query(String sql, RowMapper rowMapper) throws DataAccessException { return result(query(sql, new RowMapperResultSetExtractor(rowMapper))); } // Other methods... }

Instead of providing logic for converting an entire ResultSet object, including iteration over the rows, we can provide logic for how to convert a single row:

public class BookRowMapper implements RowMapper { @Override public Book mapRow(ResultSet rs, int rowNum) throws SQLException { Book book = new Book(); book.setId(rs.getLong("id")); book.setTitle(rs.getString("title")); book.setAuthor(rs.getString("author")); return book; } }

With this converter, we can then query a database using the JdbcTemplate and map each resulting row:

JdbcTemplate template = // create template... template.query("SELECT * FROM books", new BookRowMapper());

Apart from JDBC database management, Spring also uses templates for:

  • Java Message Service (JMS)
  • Java Persistence API (JPA)
  • Hibernate (now deprecated)
  • Transactions

6. Conclusion

In this tutorial, we looked at four of the most common design patterns applied in the Spring Framework.

Също така проучихме как Spring използва тези модели, за да предостави богати функции, като същевременно намали тежестта за разработчиците.

Кодът от тази статия може да бъде намерен в GitHub.