Java spring factory class

Create Spring Beans using Factory Methods

The advantage of using the spring framework is the efficient beans management by the IOC container. We never create an instance in the code instead spring creates and manages them. In the certain scenarios, the demand is to use the factory methods for creating the instances of an particular object due to the restriction imposed by that object for not instantiating directly by using the constructors. This requirement is very common when we are using the service locator pattern create and manage the objects. Spring provides options to inform the IOC container to use the factory methods for creating the instances. This tutorial provides simple examples to use the factory methods for creating the bean instance.

There are two types of factory methods:

  1. Static factory method : These are defined as the static methods and always have the single object instance for that class. Note that the factory method should be static, otherwise you would get an exception while creating the instance.
  2. Instance factory method: These objects are created by using the bean instance.

1. Create Factory Class

The below class defines the list of factory methods. First one is static factory method and the next two methods are instance factory methods. Before creating the factory class, also create the Java beans which needs to be act as the spring beans for our example.

Transpost.java

package javabeat.net.core.ioc; public interface Transport

package javabeat.net.core.ioc; public class Car implements Transport < public void getTransport()< System.out.println("Transport type is Car"); >>
package javabeat.net.core.ioc; public class Bus implements Transport < public void getTransport() < System.out.println("Transport type is Car"); >>

SpringService.java

package javabeat.net.core.ioc; public class SpringService < private static SpringService service = new SpringService(); //Static factory method public static SpringService createService()< return service; >//Instance factory methods public Transport createCarInstance() < return new Car(); >public Transport createBusInstance() < return new Bus(); >>

2. Configure Factory Methods in Spring Configuration

If you look at the below code snippet, first I declare factory method for creating the instance of SpringService. After that using the SpringService beans, I declare instance factory methods. The below are the important attributes for creating the factory methods.

  • factory-method: This is the key attribute for mentioning the factory methods in the class.
  • factory-bean: This is required when we need instance factory methods.
Читайте также:  image-rendering

spring-beans-ioc.xml

3. Create Context Loader

Once we are ready with all the files, lets create the test application by loading the ApplicationContext. If you run the below example, it will create three beans and invoke them. I have used ClassPathXmlApplicationContext for loading the spring configuration file.

SpringContextLoader.java

package javabeat.net.core.ioc; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringContextLoader < public static void main (String args[])< ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml"); Transport transportCar = (Transport)applicationContext.getBean("springServiceCarInstance"); transportCar.getTransport(); Transport transportBus = (Transport)applicationContext.getBean("springServiceBusInstance"); transportBus.getTransport(); applicationContext.close(); >>

I hope this example would help you to understand how to use the factory methods with spring configuration files.

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Источник

Devdiaries

Devdiaries

Design Patterns used in Spring Framework Part 2 — Creational Patterns (Factory, Builder, Singleton, Prototype).

02 Jun 2019 Michal Fabjanski 16 mins read.

  • The Factory pattern
    • Intent
    • Problem Solution
    • Structure of the Factory Pattern
    • Abstract Factory Pattern
    • Factory Pattern implementation in Spring
    • Factory Pattern popular use cases in Spring Framework
    • Intent
    • Problem Solution
    • Structure of the Builder Pattern
    • Builder Pattern implementation in Spring
    • Intent
    • Problem Solution
    • Structure of the Singleton Pattern
    • Singleton Pattern exemplary implementation in Spring
    • Singleton Pattern vs Spring Singletons
    • Intent
    • Problem Solution
    • Structure of the Prototype Pattern
    • PrototypePattern implementation in Spring

    Creational design patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. In this article, I will describe the most popular patterns in this category and how Spring uses them!

    The Factory pattern

    Spring, in itself, is already an example implementation of the Factory pattern. The pattern is used throughout the entire framework. One of the primary places it’s used is the BeanFactory class.

    Intent

    • Factory pattern allows construction of similar classes of different types using a factory method
    • Method call creates the object for you
    • Created objects are instances from classes that share an interface or subclass

    Problem Solution

    • Thanks to Factory Design Pattern you do not have to worry about class construction in more than one place.
    • It allows you to leverage the interface for repetitive operations.
    • Copy-paste bugs are less likely.

    Structure of the Factory Pattern

    Firstly, you have to create common interface that you are going to use in objects factory. Then, you need to create a class that creates instances of your inteface. In that class, you have to implement a method that servers concrete classes that you will then implement from the interface itself. So, again, we have a class that has a method that creates instances of the interface when under the coverage that it’s actually creating instances in the concrete class.

    Abstract Factory Pattern

    Abstract Factory Pattern is a pattern very similar to the Factory Pattern. You can say that it is Factory of factories. In a nutshell, there are two main differences between the Factory Pattern and Abstract Factory:

    factory-pattern-spring-java

    • Abstract Factory design pattern creates Factory
    • Factory design pattern creates Products

    There are a couple attributes, contructor and auto-generated getters. It’s time for implementing builder pattern! To do this, create the EmployeeBuilder class with the same fields as the Employee class. Generate setters — one for each of our fields. If you generate setters by IDE, you must remember to change the type returned by setter (void) to EmployeeBuilder.

    builder-pattern-spring-framework

    Now, create simple Spring @Component class without any logic:

    @Component public class SpringSingleton  >

    Next, let’s test whether our singletons ensure that only one object is created. I used the JUnit test (generated automatically when creating a Spring Boot project in Spring Initializer):

    @RunWith(SpringRunner.class) @SpringBootTest public class SpringDesignPatternsApplicationTests  @Autowired SpringSingleton springSingleton1; @Autowired SpringSingleton springSingleton2; @Test public void singletonObjectsShouldBeEquals()  Singleton singleton1 = Singleton.getInstance(); Singleton singleton2 = Singleton.getInstance(); // Checking if the Singleton objects are definitely one, the same object Assert.assertSame(singleton1, singleton2); // Checking if the spring components are definitely singletons Assert.assertSame(springSingleton1, springSingleton2); > >

    assertSame() method checks if arguments are same objects. Test result: passed — everything was the same. That`s how you can write traditional singletons or singletons in Spring.

    Singleton Pattern vs Spring Singletons

    There is one more thing you should know. As I wrote — all Spring beans are singletons by default. However, these are not the same singletons as the traditional singletons. The traditional Singleton pattern assumes that there is only one instance of a given class at the space managed by Java classloader. In Spring, there is only one instance of Bean for each given context ( _org.springframework.context.ApplicationContext ) instance. So, if you have more then one context, all managed by the same Java classloader, you will probably have more than one instance of a bean.

    The Prototype pattern

    The prototype is a pattern whose purpose is to copy objects from the parent object. In the prototype pattern, a new object is created by cloning an existing object. In Java, the clone() method is an implementation of this design pattern.

    Intent

    • Instance is cloned at runtime to give new instances that have the same state
    • In Java It’s done with the Cloneable interface/

    Problem Solution

    The prototype can be used in cases:

    • You have to create a lot of instances of the same or similar objects, and cloning is more efficient than creating instances of objects with the new Java keyword.
    • Useful with objects that must be thread safe and need to store state (e.g shopping carts — where you want to have the same behavior but the individual items in the cart are different)

    Structure of the Prototype Pattern

    • Create an abstract base class that implements Cloneable.
    • Extend abstract class in prototype instances.
    • Override the clone() method in those prototype instances — add the class specific behavior.

    PrototypePattern implementation in Spring

    I will not implement the traditional Java prototype. However, I will show you how to create a prototype bean in Spring. I created one dumb class: SpringPrototype.java

     public class SpringPrototype  >

    In the main application class in Spring, I defined defined a new prototype bean by setting @Scope to prototype:

     @Bean @Scope("prototype") public SpringPrototype prototype() return new SpringPrototype(); >
     @Autowired SpringPrototype prototype1; @Autowired SpringPrototype prototype2; @Test public void prototypeObjectsShouldNotBeEquals()  Assert.assertNotSame(prototype1, prototype2); >

    I injected two instances of the SpringPrototype class with @Autowired . Just like in the Singleton example — I used the static method from Assert to check that the created instances are not the same. My test is green. It’s proof that there are two different instances of the same object.

    Conclusion

    I hope you liked the post. We’ve got to know the most important creational patterns used in Spring. In the next post, we will learn about structural patterns in Spring Framework!

    The source code from the post is available on my Github repo.

    Источник

Оцените статью