Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts
In a previous article Introduction to Spring, we discussed What is Spring and why it so popular among Java developers and we also discussed how Spring has broken its complete framework into different-different modules based on the functionality.

Spring framework is organized into 20 modules which can again be grouped into Core Container, Web, Data Access/Integration, AOP, Aspect, Instrumentation, Messaging, and Test, as shown in the following diagram.
 spring-modules

Core container

The Core and Beans modules provide the most fundamental parts of the framework and provide the IoC and Dependency Injection features. The basic concept here is the BeanFactorywhich provides a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

The Context module builds on the solid base provided by the Core and Beans modules: it provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The Context module inherits its features from the Beans module and adds support for internationalization (I18N) (using for example resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. The Context module also contains support for some Java EE features like EJB, JMX, and basic remoting support. The ApplicationContext interface is the focal point of the Context module that provides these features.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. It can be seen as an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting of property values, property assignment, method invocation, accessing the context of arrays, collections, and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection, as well as common list aggregators.

Spring Web module

Spring's Web module provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. It also contains the web-related parts of Spring's remoting support.

The Web-Servlet module provides Spring's Model-View-Controller implementation for web-applications. Spring MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. We can also create Rest APIs using the same annotation as we use in web MVC.

The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors what is provided in the Web-Servlet module.

Data Access & Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.

The OXM module provides an abstraction layer for using a number of Object/XML mapping implementations. Supported technologies include JAXB, Castor, XMLBeans, JiBX, and XStream.

The JMS module provides Spring's support for the Java Messaging Service. It contains features for both producing and consuming messages.

The Transaction module provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces but for all your POJOs (plain old Java objects).

Spring AOP and Aspect

The Spring AOP module integrates Aspect Oriented Programming functionality directly into the Spring framework, which allows us to define segregate our cross-cutting functionalities from our business logic. As a result, we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application.

There is also a separate Aspects module that provides integration with AspectJ.

Instrumentation

The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers.

Messaging

Spring framework's messaging module serves as a foundation for messaging-based applications. The module provides a set of classes e.g., Message, MessageChannelMessageHandler to send and receive messages from the application and it also provides a set of annotations for mapping messages to methods, similar to the Spring MVC annotation based programming model.

Test

Spring framework's Test module provides abstraction over a lot of testing and mocking framework such as TestNG, JUnit, Mockito, PowerMock which makes writing unit and integration a lot easier.

Below are the dependencies for the above modules

GroupId
ArtifactId
Description
org.springframework
spring-aop
Proxy-based AOP support
org.springframework
spring-aspects
AspectJ based aspects
org.springframework
spring-beans
Beans support, including Groovy
org.springframework
spring-context
Application context runtime, including scheduling and remoting abstractions
org.springframework
spring-context-support
Support classes for integrating common third-party libraries into a Spring application context
org.springframework
spring-core
Core utilities, used by many other Spring modules
org.springframework
spring-expression
Spring Expression Language (SpEL)
org.springframework
spring-instrument
Instrumentation agent for JVM bootstrapping
org.springframework
spring-instrument-tomcat
Instrumentation agent for Tomcat
org.springframework
spring-jdbc
JDBC support package, including DataSource setup and JDBC access support
org.springframework
spring-jms
JMS support package, including helper classes to send/receive JMS messages
org.springframework
spring-messaging
Support for messaging architectures and protocols
org.springframework
spring-orm
Object/Relational Mapping, including JPA and Hibernate support
org.springframework
spring-oxm
Object/XML Mapping
org.springframework
spring-test
Support for unit testing and integration testing Spring components
org.springframework
spring-tx
Transaction infrastructure, including DAO support and JCA integration
org.springframework
spring-web
Foundational web support, including web client and web-based remoting
org.springframework
spring-webmvc
HTTP-based Model-View-Controller and REST endpoints for Servlet stacks
org.springframework
spring-webmvc-portlet
MVC implementation to be used in a Portlet environment
org.springframework
spring-websocket
WebSocket and SockJS infrastructure, including STOMP messaging support
In my previous article JPA Auditing: Persisting Audit Logs Automatically using EntityListeners, I have discussed how we can use Spring Data JPA automate Auditing and automatically create audit logs or history records and update CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties.

So in order to save history records for our File entity, we were trying to auto-wire EntityManager inside our FileEntityListener class and we have come to know that we can not do this.

We can not inject any Spring-managed bean in the EntityListener because EntityListeners are instantiated by JPA before Spring inject anything into it. EntityListeners are not managed Spring so Spring cannot inject any Spring-managed bean e.g. EntityManager in the EntityListeners.

And this case is not just with EntityListeners, you can not auto wire any Spring-managed bean into another class (i.e. utility classes) which is not managed by Spring.

Because it is a very common problem and can also arise with other classes so I tried to come out with a common solution which will not just solve this problem but will also help us getting Spring managed beans in other places.

AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners

So I have created one utility class to fetch any bean according to our requirement.

@Service
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

}

Now to get any a bean in class we will just need call the BeanUtil.getBean(YourClass.class) and pass the class type to it and we will get the bean.

For Example in our case, we were trying to get the EntityManager bean inside FileEntityListener, we can simply do it by writing BeanUtil.getBean(EntityManager.class).

public class FileEntityListener {

    private void perform(File target, Action action) {
        EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
        entityManager.persist(new FileHistory(target, action));
    }

}

You can find complete code on this Github Repository and please feel free to provide your valuable feedback.
If we talk about Java EE development then the biggest buddy that comes into the picture is Spring. So in this article, I am going to cover some brief introduction of Spring framework and then we are going to look why Spring is so popular, and in subsequent articles, I am going to cover more about Spring.

So what is Spring
  • Spring is a Lightweight, Open Source, Free to use application framework that provides comprehensive infrastructure support for developing Java-based enterprise applications. Spring handles the infrastructure and configurations so you can focus on your application.
  • It was written by Rod Johnson in June 2003 and first released under the Apache 2.0 license, And now maintained by Pivotal.
  • Spring has not reinvented everything from the scratch but it has integrated some existing technologies and frameworks like Hibernate, Struts, JSF, EJB, and more in an efficient modular architecture by integrating them very efficiently. You can use what you need and can leave those you don’t need now.

    That’s why some developers also call Spring “A framework of frameworks”, because Spring allows them to use all popular frameworks combinedly.

  • The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test, as shown in the following diagram.
    spring-modules
  • Lightweight IoC container and Transaction support have also made Spring the best replacement for costly EJB containers.
  • Spring Enables to develop enterprise applications using POJO Programming. By using POJO programming developer don’t need any EJB Container in our Application Server Instead of that only a robust Servlet Container is good. POJO programming also enables continuous integration and testability.

Why Spring is so popular

Spring became so popular in its early days because of these features
  • Lightweight: Spring is lightweight when it comes to size and transparency,
    • The basic version of the spring framework is around 1MB.
    • Processing overhead is also very negligible.
    • Due to its modular architecture, you have the option to choose what you want to include and what’s not.
    • You can also call Spring lightweight as compared to heavyweight EJB containers.
  • Loose Coupled code through Dependency Injection: Loose coupling is achieved in Spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Spring Core Container or IoC Container: Central to the Spring framework is its Ioc Container which contains and manages the lifecycle and configuration of application objects. Objects created by the container are also called managed objects or beans.
  • Aspect-oriented Programming (AOP): Spring supports Aspect Oriented Programming and enables cohesive development by separating application business logic from system services.
  • MVC Framework: Spring comes with MVC web application framework (Spring MVC), built on core Spring functionality. This framework is highly configurable via strategy interfaces and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  • Transaction Management: Spring provides a declarative transaction management interface that can scale down to a local transaction (using a single database e.g.) and scale up to global transactions (using JTA e.g.). This allows the developer to add the pluggable transaction managers and making it easy to demarcate transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE environments and it can be also used in the container-less environments.
  • Convenient Exception Handling: Spring provides a convenient API for translating technology-specific exceptions (thrown by JDBC, Hibernate, or JDO e.g.) into consistent, meaningful, unchecked exceptions which describe more about itself.
Previous Post Older Posts Home