Pola Desain dalam Kerangka Musim Semi

1. Perkenalan

Pola desain adalah bagian penting dari pengembangan perangkat lunak. Solusi ini tidak hanya memecahkan masalah yang berulang tetapi juga membantu pengembang memahami desain kerangka kerja dengan mengenali pola umum.

Dalam tutorial ini, kita akan melihat empat pola desain paling umum yang digunakan dalam Spring Framework:

  1. Pola tunggal
  2. Pola Metode Pabrik
  3. Pola proxy
  4. Pola template

Kami juga akan melihat bagaimana Spring menggunakan pola ini untuk mengurangi beban pengembang dan membantu pengguna melakukan tugas yang membosankan dengan cepat.

2. Pola Singleton

Pola tunggal adalah mekanisme yang memastikan hanya satu contoh objek yang ada per aplikasi . Pola ini dapat berguna saat mengelola sumber daya bersama atau menyediakan layanan lintas sektor, seperti penebangan.

2.1. Kacang Singleton

Umumnya, singleton secara global unik untuk suatu aplikasi, tetapi di Spring, batasan ini dilonggarkan. Sebaliknya, Spring membatasi satu objek tunggal ke satu objek per kontainer Spring IoC . Dalam praktiknya, ini berarti Spring hanya akan membuat satu kacang untuk setiap jenis per konteks aplikasi.

Pendekatan Spring berbeda dari definisi ketat singleton karena aplikasi dapat memiliki lebih dari satu container Spring. Oleh karena itu, beberapa objek dari kelas yang sama dapat berada dalam satu aplikasi jika kita memiliki banyak kontainer.

Secara default, Spring membuat semua kacang sebagai lajang.

2.2. Autowired Singletons

Misalnya, kita dapat membuat dua pengontrol dalam satu konteks aplikasi dan menyuntikkan kacang dengan tipe yang sama ke masing-masing.

Pertama, kami membuat BookRepository yang mengelola objek domain Book kami .

Selanjutnya, kami membuat LibraryController , yang menggunakan BookRepository untuk mengembalikan jumlah buku di perpustakaan:

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

Terakhir, kami membuat BookController , yang berfokus pada tindakan spesifik Buku , seperti menemukan buku berdasarkan ID-nya:

@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(); } }

Kami kemudian memulai aplikasi ini dan melakukan GET on / count dan / book / 1:

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

Dalam keluaran aplikasi, kita melihat bahwa kedua objek BookRepository memiliki ID objek yang sama:

[email protected] [email protected]

The BookRepository ID objek dalam LibraryController dan BookController adalah sama, membuktikan bahwa musim semi disuntikkan kacang sama ke kedua kontroler.

Kita dapat membuat instance terpisah dari kacang BookRepository dengan mengubah lingkup kacang dari tunggal ke prototipe menggunakan anotasi @ Scope (ConfigurableBeanFactory.SCOPE_PROTOTYPE) .

Melakukannya menginstruksikan Spring untuk membuat objek terpisah untuk setiap kacang BookRepository yang dibuatnya. Oleh karena itu, jika kita memeriksa lagi ID objek BookRepository di masing-masing pengontrol kita, kita melihat bahwa mereka tidak lagi sama.

3. Pola Metode Pabrik

Pola metode pabrik memerlukan kelas pabrik dengan metode abstrak untuk membuat objek yang diinginkan.

Seringkali, kami ingin membuat objek yang berbeda berdasarkan konteks tertentu.

Misalnya, aplikasi kita mungkin memerlukan objek kendaraan. Di lingkungan bahari, kami ingin membuat perahu, tetapi di lingkungan luar angkasa, kami ingin membuat pesawat:

Untuk mencapai ini, kita dapat membuat implementasi pabrik untuk setiap objek yang diinginkan dan mengembalikan objek yang diinginkan dari metode pabrik beton.

3.1. Konteks Aplikasi

Spring menggunakan teknik ini di root framework Dependency Injection (DI).

Pada dasarnya, Spring memperlakukan wadah kacang sebagai pabrik yang memproduksi kacang.

Jadi, Spring mendefinisikan antarmuka BeanFactory sebagai abstraksi wadah kacang:

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

Setiap metode getBean dianggap sebagai metode pabrik , yang mengembalikan kacang yang cocok dengan kriteria yang diberikan ke metode, seperti jenis dan nama kacang.

Spring kemudian memperluas BeanFactory dengan antarmuka ApplicationContext , yang memperkenalkan konfigurasi aplikasi tambahan. Spring menggunakan konfigurasi ini untuk memulai wadah kacang berdasarkan beberapa konfigurasi eksternal, seperti file XML atau penjelasan Java.

Using the ApplicationContext class implementations like AnnotationConfigApplicationContext, we can then create beans through the various factory methods inherited from the BeanFactory interface.

First, we create a simple application configuration:

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

Next, we create a simple class, Foo, that accepts no constructor arguments:

@Component public class Foo { }

Then create another class, Bar, that accepts a single constructor argument:

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

Lastly, we create our beans through the AnnotationConfigApplicationContext implementation of 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.

Kami juga mempelajari cara Spring menggunakan pola ini untuk menyediakan fitur yang kaya sekaligus mengurangi beban developer.

Kode dari artikel ini dapat ditemukan di GitHub.