SlideShare une entreprise Scribd logo
1  sur  37
Spring Framework
-by Kamal
What is Spring?
lIt is a Java Application Development Framework
lSimplifies development (Imp)
lReduces boilerplate code
lLoose Coupling
lImproves Testability
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.
POJOs
lNeed not learn complex frameworks and
technologies like struts or EJBs
lFramework does not interfere with code logic
public class HelloWorldAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
<struts-config>
<form-beans>
<form-bean name="helloWorldForm"
type="com.mkyong.common.form.HelloWorldForm"/>
</form-beans>
<action-mappings>
<action path="/helloWorld"
type="com.mkyong.common.action.HelloWorldAction"
name="helloWorldForm">
<forward name="success" path="/HelloWorld.jsp"/>
</action>
</action-mappings>
</struts-config>
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();
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.
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
address=new Address(‘some values here’);
}
}
Simple Employee Class
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
Contructor Injection
class Employee{
public Address address;
Employee(Address address)
{
this.address=address;
}
}
Setter Injection
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
}
public void setAddress(Address address)
{
this.address=address;
}
}
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>
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.
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
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
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
@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
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.
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.
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");
@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);
Spring bean life cycle
Spring MVC
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring_config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
Add to Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and your base-package here:-->
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan
base-package="com.abc.service"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000"/>
</bean>
</beans>
Config file
@Controller
@RequestMapping("/login")
public class LoginController {
/**
* This method authenticates user against username and password.
*
* @param username
* @param password
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String getCandidates(
@RequestParam("username") String username,
@RequestParam("password") String password) {
UserDAO userDAO = new UserDAO();
if (userDAO.validateUser(username, password))
return "success";
return "sorry";
}
}
Controller class
Spring Security
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Modifications in web.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
</beans>
Modificaitons in Config
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
@PreAuthorize("hasPermission(#contact, 'admin')")
public void deletePermission(Contact contact, Sid recipient, Permission permission);
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="mkyong" password="123456" authorities="ROLE_USER" />
<user name="admin" password="123456" authorities="ROLE_ADMIN" />
<user name="dba" password="123456" authorities="ROLE_DBA" />
</user-service>
</authentication-provider>
</authentication-manager>
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
.and().formLogin();
}
}
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
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
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..
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
References
http://spring.io/
http://docs.spring.io/spring-
framework/docs/current/spring-framework-
reference/html/overview.html#overview-modules
http://kamalmeet.com/tag/spring/
http://www.mkyong.com/spring-security/spring-
security-hello-world-annotation-example/
Book: Learning Spring Application development
Book: Spring Enterprise Recipes
Book: Spring in Action

Contenu connexe

Tendances (20)

02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Java Programming - 01 intro to java
Java Programming - 01 intro to javaJava Programming - 01 intro to java
Java Programming - 01 intro to java
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
SQL injection: Not only AND 1=1
SQL injection: Not only AND 1=1SQL injection: Not only AND 1=1
SQL injection: Not only AND 1=1
 
Java 9
Java 9Java 9
Java 9
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Struts notes
Struts notesStruts notes
Struts notes
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
7.Spring DI_2
7.Spring DI_27.Spring DI_2
7.Spring DI_2
 
Annotations
AnnotationsAnnotations
Annotations
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Spring 3 to 4
Spring 3 to 4Spring 3 to 4
Spring 3 to 4
 
Spring
SpringSpring
Spring
 

Similaire à Spring Framework: A Popular Java Application Development Framework

[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malavRohit malav
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 

Similaire à Spring Framework: A Popular Java Application Development Framework (20)

[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Struts 1
Struts 1Struts 1
Struts 1
 
Get ready for spring 4
Get ready for spring 4Get ready for spring 4
Get ready for spring 4
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Signal Framework
Signal FrameworkSignal Framework
Signal Framework
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malav
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 

Spring Framework: A Popular Java Application Development Framework

  • 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
  • 5. public class HelloWorldAction extends Action{ public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception { <struts-config> <form-beans> <form-bean name="helloWorldForm" type="com.mkyong.common.form.HelloWorldForm"/> </form-beans> <action-mappings> <action path="/helloWorld" type="com.mkyong.common.action.HelloWorldAction" name="helloWorldForm"> <forward name="success" path="/HelloWorld.jsp"/> </action> </action-mappings> </struts-config>
  • 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
  • 10. Contructor Injection class Employee{ public Address address; Employee(Address address) { this.address=address; } }
  • 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);
  • 25.
  • 27. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Uncomment and your base-package here:--> <mvc:annotation-driven /> <context:annotation-config /> <context:component-scan base-package="com.abc.service"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="50000000"/> </bean> </beans> Config file
  • 28. @Controller @RequestMapping("/login") public class LoginController { /** * This method authenticates user against username and password. * * @param username * @param password * @return */ @RequestMapping(method = RequestMethod.GET) public @ResponseBody String getCandidates( @RequestParam("username") String username, @RequestParam("password") String password) { UserDAO userDAO = new UserDAO(); if (userDAO.validateUser(username, password)) return "success"; return "sorry"; } } Controller class
  • 32. @PreAuthorize("hasRole('ROLE_USER')") public void create(Contact contact); @PreAuthorize("hasPermission(#contact, 'admin')") public void deletePermission(Contact contact, Sid recipient, Permission permission); <http auto-config="true"> <intercept-url pattern="/admin**" access="ROLE_ADMIN" /> <intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="mkyong" password="123456" authorities="ROLE_USER" /> <user name="admin" password="123456" authorities="ROLE_ADMIN" /> <user name="dba" password="123456" authorities="ROLE_DBA" /> </user-service> </authentication-provider> </authentication-manager> @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN"); auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')") .and().formLogin(); } }
  • 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