Spring Framework is a popular Java application development framework that simplifies development and reduces boilerplate code. Its core features include dependency injection, aspect-oriented programming, and lightweight containers. Spring supports both XML and annotation-based configuration and provides abstraction for data access technologies like JPA. It also includes additional modules for web applications (Spring MVC), REST services, security, and more. The framework has evolved over several versions to add new features and improve existing capabilities.
2. What is Spring?
lIt is a Java Application Development Framework
lSimplifies development (Imp)
lReduces boilerplate code
lLoose Coupling
lImproves Testability
3. Core Features
lEmpowers POJOs
lDependency Injection support in container
lAOP support
lLight Weight - Fast
lAnnotation driven
lBuffet of frameworks
lSupports both XML and annotation-based
configuration.
lProvides abstraction on ORM
lThe Spring Test module provides support for an
easy-to-test code.
4. POJOs
lNeed not learn complex frameworks and
technologies like struts or EJBs
lFramework does not interfere with code logic
6. import xyz;
import abc;
@Controller
@RequestMapping("/report")
public class ReportController {
/**
* Entry point for serving an application report
*
*/
@RequestMapping("/fetch)
public void applicationReport(HttpServletResponse response) {
final ApplicationExcelReport report = new ApplicationExcelReport();
final long startMillis = System.currentTimeMillis();
final HSSFWorkbook workbook =
report.getSubmittedApplicationsReport();
final long endMillis = System.currentTimeMillis();
7. DI
lIoC is a more general concept, whereas DI is a
concrete design pattern.
lLoosely coupled architecture.
lSeparation of responsibility.
lConfiguration and code are separate.
lA different implementation can be supplied using
configuration without changing the code
dependent.
lImproves testability.
8. Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
address=new Address(‘some values here’);
}
}
Simple Employee Class
9. Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
//check if employee has local address
address=new AddressFactory.getAddress(“LocalAddress”);
//else case get permanent address
}
}
Adding complexity
11. Setter Injection
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
}
public void setAddress(Address address)
{
this.address=address;
}
}
12. In Spring
Class Employee
{
public Address address;
public String name;//other stuff
@Autowired
Employee(Address address)
{
this.address=address
}
}
<bean id="AddressBean" class="com.test.Address">
<property name="street" value="43rd" />
<property name="apt" value="29" />
<property name="city" value="New york" />
</bean>
13. AOP
lIsolates non-core functionalities from code logic
*Cross cutting concerns are the functionalities
which are distributed accross the application but
are not part of any core module.
14. public class Employee {
int id;
String name;
public Employee(int id, String name)
{
this.id=id;
this.name=name;
}
public void work()
{
System.out.println(“Employee:”+ name+” is
working”);
}
}
Simple Employee Class
15. public class BookKeeper {
java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new
Timestamp(date.getTime()));
}
/**
* This method indicates when employee has stopped working
*/
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new
Timestamp(date.getTime()));
}
}
BookKeeper
16. public class Employee {
int id;
String name;
BookKeeper bookKeeper=new BookKeeper();
public Employee(int id, String name)
{
this.id=id;
this.name=name;
}
public void work()
{
bookKeeper.employeeStartsWorking();
System.out.println(“Employee:”+ name+” is working”);
bookKeeper.employeeEndsWorking();
}
}
Modified Employee
17. @Component
@Aspect
public class BookKeeper {
java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
@Before(“execution(* com.test.*.*(..))”)
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new
Timestamp(date.getTime()));
}
/**
* This method indicates when employee has stopped working
*/
@After(“execution(* com.test.*.*(..))”)
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new
Timestamp(date.getTime()));
}
}
With AOP
18. The Buffet
lSpring Core- container with DI, Bean, Context
lSpring MVC
lSpring Web Services/ REST
lSpring DATA- Spring Data JPA, Spring Data MongoDB,
Spring Data redis etc
lSpring Security
lSpring Batch
lSpring Social – (core, facebook, twitter etc) enables
connectvity with social networking websites
lSpring Mobile- to serve alternative views for different devices.
19.
20. lCore module: It provides features such as IoC and Dependency Injection.
lBeans module: The bean module in Spring Core Container provides
BeanFactory, which is a generic factory pattern that separates the dependencies
such as initialization, creation, and access of the objects from your actual
program logic. BeanFactory in Spring Core Container supports the following two
scopes modes of object:
l Singleton
l Prototype or non-singleton
lContext module: An ApplicationContext container loads Spring bean definitions
and wires them together.
lExpression language: Spring Expression Language (SpEL) is a powerful
expression language supporting the features for querying and manipulating an
object graph at runtime. SpEL can be used to inject bean or bean property in
another bean. SpEL supports method invocation and retrieval of objects by
name from IoC container in Spring.
21. Example-
lXML-based bean configuration
l<?xml version="1.0" encoding="UTF-8"?>
l<beans xmlns="http://www.springframework.org/schema/beans"
l xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
l xsi:schemaLocation="http://www.springframework.org/schema/beans
l http://www.springframework.org/schema/beans/spring-beans.xsd">
l <bean id="..." class="...">
l <!-- configuration for this bean here -->
l </bean>
l <!-- more bean definitions here -->
l</beans>
l<bean id="employeeBean"
l class="src.org.packt.Spring.chapter2.Employee">
lBeanFactory bfObj = new XmlBeanFactory (new FileSystemResource
("c:/beans.xml"));
lMyBean beanObj= (MyBean) bfObj.getBean ("mybean");
22. @Configuration
@MapperScan("com.bsd.acm.data.mapper")
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.bsd.acm, com.bsd.acm.service")
public class AppConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
return sessionFactory.getObject();
}
private static AnnotationConfigApplicationContext context;
static {
context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.refresh();
}
service = context.getBean(IGroupService.class);
33. A Brief History
lSpring 1.0 (2004)
l Spring Core: This is a lightweight container with various setter and
constructor injection
l Spring AOP: This is an Aspect-oriented Programming (AOP) interception
framework integrated with the core container
l Spring Context: This is an application context concept to provide resource
loading
l Spring DAO: This is a generic DAO support that provides access to a
generic data exception hierarchy with any data access strategy
l Spring JDBC: This is a JDBC abstraction shorten error and resource
handling
l Spring ORM: This is a hibernate support SessionFactory management
l Spring Web: This web MVC Framework integrates various view
technologies
34. Contd..
lSpring 2.x (2006)
l Improvements in the IoC container and AOP, including the @AspectJ
annotation support for AOP development
l Introduction of bean configuration dialects
l XML-based configuration is reduced and XML schema support and
custom namespace is introduced
l Annotation-driven configuration that requires component scanning to
auto-detect annotated components in the classpath using annotations such
as @Component or specialized annotations such as @Repository,
@Service, and @Controller
l Introduces annotations such as @RequestMapping, @RequestParam,
and @ModelAttribute for MVC controllers
35. lSpring 3.x (2009)
lSupports REST in Spring MVC, which is one of the beautiful additions to the
Spring Framework itself.
lIntroduces new annotations @CookieValue and @RequestHeader for
pulling values from cookies and request headers, respectively. It also
supports new XML namespace that makes easier to configure Spring MVC.
lTask scheduling and asynchronous method execution with annotation
support is introduced to this version.
lIntroduces annotation called @Profile, which is used while applying
configuration classes.
lIntroduces PropertySource that is an abstraction performed over any
different source of the key-value pairs. In DefaultEnvironment, there are two
configured PropertySource objects: System.getProperties() and
System.getenv().
lHibernate 4.x is supported by this release through Java Persistence API
(JPA).
lIntroduces @RequestPart annotation to provide access to multipart form-
data content on the controller method arguments.
Contd..
36. lSpring 4.x
lAuto-wiring is based on generic types
lIntroduces the @Description annotation
lIntroduces @Conditional that can conditionally filter
the beans.
lIntroduces the @Jms annotation to support
annotation-driven endpoint
lCatching support is revisited, provided
CacheResolver to resolve caches at runtime
lAdded new testing features such as SQL Script
execution, bootstrap strategy, and so on
lAdded lightweight messaging and WebSocket-style
architectures
Latest