Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Spring Framework
-by Kamal
What is Spring?
lIt is a Java Application Development Framework
lSimplifies development (Imp)
lReduces boilerplate code
lL...
Core Features
lEmpowers POJOs
lDependency Injection support in container
lAOP support
lLight Weight - Fast
lAnnotation dri...
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,
HttpServ...
import xyz;
import abc;
@Controller
@RequestMapping("/report")
public class ReportController {
/**
* Entry point for servi...
DI
lIoC is a more general concept, whereas DI is a
concrete design pattern.
lLoosely coupled architecture.
lSeparation of ...
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
address=new Address(‘some values he...
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
//check if employee has local addre...
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 setA...
In Spring
Class Employee
{
public Address address;
public String name;//other stuff
@Autowired
Employee(Address address)
{...
AOP
lIsolates non-core functionalities from code logic
*Cross cutting concerns are the functionalities
which are distribut...
public class Employee {
int id;
String name;
public Employee(int id, String name)
{
this.id=id;
this.name=name;
}
public v...
public class BookKeeper {
java.util.Date date= new java.util.Date();
/**
* This method records when employee has started w...
public class Employee {
int id;
String name;
BookKeeper bookKeeper=new BookKeeper();
public Employee(int id, String name)
...
@Component
@Aspect
public class BookKeeper {
java.util.Date date= new java.util.Date();
/**
* This method records when emp...
The Buffet
lSpring Core- container with DI, Bean, Context
lSpring MVC
lSpring Web Services/ REST
lSpring DATA- Spring Data...
lCore module: It provides features such as IoC and Dependency Injection.
lBeans module: The bean module in Spring Core Con...
Example-
lXML-based bean configuration
l<?xml version="1.0" encoding="UTF-8"?>
l<beans xmlns="http://www.springframework.o...
@Configuration
@MapperScan("com.bsd.acm.data.mapper")
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.bsd.acm, ...
Spring bean life cycle
Spring MVC
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet<...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3...
@Controller
@RequestMapping("/login")
public class LoginController {
/**
* This method authenticates user against username...
Spring Security
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilte...
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"...
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
@PreAuthorize("hasPermission(#contact, 'admin')...
A Brief History
lSpring 1.0 (2004)
l Spring Core: This is a lightweight container with various setter and
constructor inje...
Contd..
lSpring 2.x (2006)
l Improvements in the IoC container and AOP, including the @AspectJ
annotation support for AOP ...
lSpring 3.x (2009)
lSupports REST in Spring MVC, which is one of the beautiful additions to the
Spring Framework itself.
l...
lSpring 4.x
lAuto-wiring is based on generic types
lIntroduces the @Description annotation
lIntroduces @Conditional that c...
References
http://spring.io/
http://docs.spring.io/spring-
framework/docs/current/spring-framework-
reference/html/overvie...
Spring
Spring
Upcoming SlideShare
Loading in …5
×

Spring

632 views

Published on

  • Be the first to comment

  • Be the first to like this

Spring

  1. 1. Spring Framework -by Kamal
  2. 2. What is Spring? lIt is a Java Application Development Framework lSimplifies development (Imp) lReduces boilerplate code lLoose Coupling lImproves Testability
  3. 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. 4. POJOs lNeed not learn complex frameworks and technologies like struts or EJBs lFramework does not interfere with code logic
  5. 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. 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. 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. 8. Class Employee { public Address address; public String name;//other stuff Employee() { address=new Address(‘some values here’); } } Simple Employee Class
  9. 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. 10. Contructor Injection class Employee{ public Address address; Employee(Address address) { this.address=address; } }
  11. 11. Setter Injection Class Employee { public Address address; public String name;//other stuff Employee() { } public void setAddress(Address address) { this.address=address; } }
  12. 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. 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. 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. 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. 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. 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. 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. 19. 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.
  20. 20. 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");
  21. 21. @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);
  22. 22. Spring bean life cycle
  23. 23. Spring MVC
  24. 24. <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
  25. 25. <?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
  26. 26. @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
  27. 27. Spring Security
  28. 28. <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
  29. 29. <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
  30. 30. @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(); } }
  31. 31. 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
  32. 32. 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
  33. 33. 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..
  34. 34. 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
  35. 35. 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

×