An Introduction to Spring

综合技术 DZone (源链)

Spring is an application framework well-known for enterprise application development. Its ability to enable software developers to implement systems of almost any size, including banking, ERP, e-commerce, POS, and beyond, is remarkable. Spring is built using the Java language. The latest version of the framework, Spring 5, now has support for reactive web applications. Furthermore, reactive applications are applications that adhere to the Reactive Manifesto. Being reactive means that a system is resilient, responsive, message-driven, and elastic. In this article, we will discover the basic crucial concept of Spring.

Spring IOC

At the forefront of any Spring-based application is the Spring container, where all Spring-managed beans are stored and retrieved for instantiation. The main advantages of the container are to decouple the “plumbing” code from the actual business logic. The plumbing code includes things like object instantiation, database configuration, queuing configuration in case of messaging systems… and the list goes on. Further, the business logic comprises all the application logic specified by the business requirements/specifications.

The Bean Factory

The Spring container is implemented through the BeanFactory component of the framework. BeanFactory is an implementation of the factory design pattern as described by the Gang of Four.

The Application Context

The application context is an extension of the BeanFactory component, meaning the application context is a more feature-rich version of the BeanFactory.

Annotations

Spring has a wide variety of powerful annotations such as @Qualifier, @Repository, @Service, @Controller, @RestController, @Configuration, and @Component.

@Component

This annotation is used to simply register a POJO or bean in the Spring container (i.e. to make a Spring aware of the POJO’s existence).

Example:

// The configuration class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {

    @Bean(name = "Greeting")
    public Greeting getGreetingBean() {
        return new Greeting();
    }
}

// the bean class
import org.springframework.stereotype.Component;
@Component
public class Greeting {
   public void greet() {
     system.out.println("Hello World!")
   }
}

// Client application
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
  public static void main (String args[]) {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    Greeting greetingObject = (Greeting) applicationContext.getBean("Greeting");
System.out.println(greetingObject.greet());
  }
}

@Repository

The @Repository
annotation
is a more specialized version of the @Compoment annotation and it is primarily used to annotate persistence layer classes. The added benefit of using this specialized annotation in the persistence layer is to add exception translation.

Example: 

// The configuration class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
    @Bean(name = "ProductRepository")
    public ProductRepository getProductRepositoryBean() {
        return new ProductRepository();
    }
}

// the bean class
import org.springframework.stereotype.Component;
@Repository
public class ProductRepository {
   public void save() {
     system.out.println("Product Saved.")
   }
}

// Client application
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
  public static void main (String args[]) {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    ProductRepository productRepository = (ProductRepository) applicationContext.getBean("ProductRepository");
    System.out.println(productRepository.save());
  }
}

@Service

The @Service
annotation
is a more specialized version of the @Compoment annotation and it is primarily used to annotate service layer classes.

Example: 

// The configuration class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
    @Bean(name = "ProductService")
    public ProductService getProductServiceBean() {
        return new ProductService();
    }
}

// the bean class
import org.springframework.stereotype.Component;
@Service
public class ProductService {
   public void isProductOutOfStock() {
     system.out.println(true)
   }
}

// Client application
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
  public static void main (String args[]) {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    ProductService productService = (ProductService) applicationContext.getBean("ProductService");
System.out.println(productService.isProductOutOfStock());
  }
}

@Controller

The @Controller
annotation
is a more specialized version of the @Compoment annotation and it is primarily used to annotate presentation layer classes (spring-mvc).

Example:

// The configuration class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
    @Bean(name = "ProductService")
    public ProductService getProductServiceBean() {
        return new ProductService();
    }
}

// the bean class
import org.springframework.stereotype.Component;
@Controller
public class ProductController {
   @Autowire
   private ProductService productService;

   @RequestMapping(value = "/product", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
   public void create(@RequestBody Product product) {
     productService.save(product)
     return ResponseEntity.ok().build();
   }
}

// Client application
in order to fully test this newly created enpoint, an application server 
such as tomcat will be required. Application servers are beyond the scope of this article.

@Configuration

The @Configuration
annotation
is a more specialized version of the @Compoment annotation and it is primarily used to annotate Configuration classes (i.e. classes that will contain the “plumbing” code).

@Qualifier

This annotation is used to register two beans that have the same interface but different implementations. The Qualifier annotation enables the client application to specify which implementation must be instantiated.

Example:

// Service interface
public interface SalesService {
public void registerSale(Sale sale);
} 

// cash sale implementation
@Qualifier('CashSale')
@Service
public class CashSale implements SaleService {
  public void registerSale(Sale sale){
    System.out.println("registering cash sale.")
  }
}

@Qualifier('CardSale')
@Service
public class CardSale implements SaleService {
  public void registerSale(Sale sale){
     System.out.println("registering card sale.")
  }
}

// client application
public class Application {
@Autowire
  @Qualifier('CardSale')
  private CardSale cardSale;

  @Autowire
  @Qualifier('CashSale')
  private CashSale cashSale;

  //a Dummy method just to demonstrate how the different implementations could be used.
  public void performSale(Sale sale) {
      if (sale.getSaleType == "Cash") {
      cashSale.registerSale(sale)
      } else if (sale.getSaleType == "Card") {
      cardSale.registerSale(sale)
      }
    }

@Autowire

The @Autowire annotation is used to instantiate objects that are registered with Spring.

Putting It All Together

In this article, we discovered some of the Spring framework’s main concepts. Spring has become a very large and modular application framework. It now has modules that also serve as the abstractions for almost all popular systems such as Facebook, Twitter, etc. Some of these abstractions, as per the spring website, are Spring Social Facebook, Spring Social LinkedIn, and Spring Social Twitter. Other abstractions include the Spring data project, which is useful for the persistence layer.

DZone责编内容来自:DZone (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » An Introduction to Spring

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录