SlideShare a Scribd company logo
1 of 53
Download to read offline
Java EE Leve
Uma introdução ao framework Spring


          David Ricardo do Vale Pereira
            david@jeebrasil.com.br
O que é Spring?

 Interface21
O que é Spring?


• Reduzir a complexidade do
  desenvolvimento Java EE

• Simplificar sem perder o poder

• Facilitar o desenvolvimento usando as boas
  práticas
O que é Spring?


• Possibilitar que as aplicações sejam
  construídas com POJOs

• Aplicação de serviços aos POJOs de
  maneira declarativa

  – Ex: @Transactional
O que é Spring?

Poder para os POJOs
O que é Spring?

            Spring influenciou...

– EJB 3.0

– Java Server Faces
O que é Spring?

•   Container de DI
•   AOP
•   Acesso a dados (JDBC, Hibernate, iBatis...)
•   Gerenciamento de Transações
•   Agendamento de Tarefas
•   Mail Support
•   Remoting
•   Spring MVC + Spring Web Flow
•   Spring RCP
Injeção de Dependências

         Inversão de Controle

“Inversion of Control (IoC) is a design
 pattern that addresses a component's
 dependency resolution, configuration and
 lifecycle.”

           (Paul Hammant - PicoContainer)
Injeção de Dependências


Dependency Lookup x Dependency Injection
Injeção de Dependências



  The Hollywood Principle:




Don't call us, we'll call you!
Injeção de Dependências

     Injeção de Dependências



                  Inversion of Control Containers
                   and The Dependency Injection
                              Pattern
                http://www.martinfowler.com/articles/injection.html




Martin Fowler
Injeção de Dependências

         Exemplo



         depende de
Bean 1                Bean 2
Injeção de Dependências

        Sem Inversão de Controle


public class Bean1 {
    private Bean2 bean2;
    public void metodo() {
        bean2 = new Bean2(); // sem IoC
        bean2.usandoBean();
    }

}
Injeção de Dependências

         Com Dependency Lookup


public class Bean1 {
    private Bean2 bean2;
    public void metodo() {
        bean2 = Factory.getBean2(); // Factory (GoF)
        bean2.usandoBean();
    }

}
Injeção de Dependências

        Com Dependency Injection

public class Bean1 {
    private Bean2 bean2;
    public void metodo() {
         bean2.usandoBean();
    }
    public void setBean2(Bean2 bean2) {
         this.bean2 = bean2;
    }
}
Injeção de Dependências

                Dois tipos...

– Setter Injection

– Constructor Injection



         Spring trabalha com ambos!
Injeção de Dependências

             Setter Injection

<bean id=”bean2” class=”pacote.Bean2”/>

<bean id=”bean1” class=”pacote.Bean1”>
  <property name=”bean2”>
     <ref bean=”bean2”/>
  </property>
</bean>
Injeção de Dependências

          Constructor Injection

<bean id=”bean2” class=”pacote.Bean2”/>

<bean id=”bean1” class=”pacote.Bean1”>
  <constructor-arg>
     <ref bean=”bean2”/>
  </constructor-arg>
</bean>
AOP

AOP = Aspects Oriented Programming




             Aspectos
AOP




 0
AOP

• Advices
  – Before Advice

  – After Advice

  – Around Advice

  – Throws Advice

  – Introduction Advice
AOP

      Um “Hello World!” com AOP



public class MessageWriter {
   public void writeMessage() {
      System.out.println(“World”);
   }
}
AOP

public class MessageDecorator implements
  MethodInterceptor {

    public Object invoke(MethodInvocation
                 invocation) throws Throwable {
       System.out.println(“Hello ”);
       invocation.proceed();
       System.out.println(“!”);
       return retVal;
    }

}
AOP

public class HelloWorldAOPExample {
    public static void main(String args[]) {
        MessageWriter target = new MessageWriter();


        ProxyFactory pf = new ProxyFactory();
        pf.addAdvice(new MessageDecorator());
        pf.setTarget(target);
        MessageWriter proxy = (MessageWriter)pf.getProxy();


        target.writeMessage();
        proxy.writeMessage();
    }
}
Acesso a Dados

Acesso a Dados com Spring
Acesso a Dados

            Spring com JDBC

• Gerenciamento de DataSources

• JDBC Templates

• SQLExceptionTranslator
Acesso a Dados
Acesso a Dados

            Gerenciamento de DataSources
<bean id=”dataSource”
  class=”org.springframework.jndi.JndiObjectFactoryBean”>
    <property name=”jndiName”>
    <value>java:comp/env/jdbc/meuDataSource</value>
    </property>
</bean>


<bean id=”meuDAO” class=”net.java.dev.javarn.dao.MeuDAO”>
    <property name=”dataSource”>
          <ref local=”dataSource”/>
    </property>
</bean>
Acesso a Dados

              JDBC Templates

• Facilita a execução de consultas

• Torna o código mais limpo
Acesso a Dados

int count = 0;
try {
    PreparedStatement st = getConnection().
           prepareStatement(“select count(*) from produto”);
    ResultSet rs = st.executeQuery();
    if (rs.next())
        count = rs.getInt(1);
} catch(SQLException e) {
   log.error(e);
} finally {
    try { if (stmt != null) stmt.close(); }
    catch(SQLException e) { log.warn(e); }
    try { if (conn != null) conn.close(); }
    catch(SQLException e) { log.warn(e); }
}
Acesso a Dados




JdbcTemplate jt = new JdbcTemplate(getDataSource());
int count = jt.queryForInt(
                    “select count(*) from produto”);
Acesso a Dados

<bean id=quot;jdbcTemplatequot;
  class=quot;org.springframework.jdbc.core.JdbcTemplatequot;>
   <property name=quot;dataSourcequot;>
   <ref bean=quot;dataSourcequot;/>
   </property>
</bean>



<bean id=quot;studentDaoquot; class=quot;StudentDaoJdbcquot;>
   <property name=quot;jdbcTemplatequot;>
   <ref bean=quot;jdbcTemplatequot;/>
   </property>
</bean>
Acesso a Dados

        SQLExceptionTranslator

                    BadSqlGrammarException


                    CannotGetJdbcConnectionException

SQLException
                    InvalidResultSetAccessException


                    IncorrectResultSetColumnCountException


                    ...
Acesso a Dados

          Spring com Hibernate

• Gerenciamento de Session Factories

• Hibernate DAO Support
Acesso a Dados

      Gerenciamento de Session Factories
<bean id=”dataSource” ... />

<bean id=”sessionFactory”
   class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
   <property name=”dataSource”><ref local=”dataSource”/></property>
   <property name=”hibernateProperties”>
     <props><prop key=”hibernate.dialect”>
       org.hibernate.dialect.PostgreSQLDialect
     </prop></props>
   </property>
   <property name=”mappingResources”>
      <list>
         <value>Bean1.hbm.xml</value> <value>Bean2.hbm.xml</value>
      </list>
   </property>                               ...
Acesso a Dados

              Hibernate DAO Support
public class AlunoDao extends HibernateDaoSupport implements Dao {
   public Object get(int id) {
      return getHibernateTemplate().load(Aluno.class, id);
   }
   public List getAll() {
      return getHibernateTemplate().loadAll(Aluno.class);
   }
   public void saveOrUpdate(Object o) {
      getHibernateTemplate().saveOrUpdate(o);
   }
   public List findAlunosReprovados() {
     return getHibernateTemplate().find(“from Aluno a where
                    a.disciplinas.media < ?”, new Object[] { 7 });
   }

}
Acesso a Dados


<bean id=quot;sessionFactoryquot; .../>


<bean id=quot;daoquot; class=quot;net.java.dev.javarn.TestDaoquot;>
    <property name=quot;sessionFactoryquot;>
          <ref bean=quot;sessionFactoryquot; />
    </property>
</bean>
Gerenciamento de Transações
Gerenciamento de Transações


@Transactional
public interface FooService {

    Foo getFoo(String fooName);

    void insertFoo(Foo foo);

    void updateFoo(Foo foo);
}
Gerenciamento de Transações

public class FooService {

    public Foo getFoo(String fooName) { ... }

    @Transactional(propagation =
                         Propagation.REQUIRES_NEW)
    public void updateFoo(Foo foo) {
       // ...
    }
}
Spring na Web

        Integração com Frameworks

•   Spring   +   Spring MVC
•   Spring   +   Java Server Faces
•   Spring   +   Webwork
•   Spring   +   Tapestry
•   Spring   +   Struts
Spring na Web

             Spring Web Flow

• Controle de fluxo de aplicações web

• Continuations

• Problema do botão voltar (back x undo)
Spring na Web


/step1.do
                                   storeForm

      page1
                   Controller 1                 HTTP
                                               Session


 /step2.do
                                  updateForm

      page2
                   Controller 2



/lastStep.do
                                                 Business
                                                  Service
                                  processTx
confirmationPage
                   Controller 3
Spring na Web
Spring na Web


• Fluxo como uma máquina de estados

• Estados e transições configurados com XML

• Atualmente compatível com Spring MVC e
  Java Server Faces

• Suporte a AJAX
Spring no Desktop

                 Spring RCP

• Rich Client Platform

• Programação Desktop com o poder do
  Spring

• Suporte a Swing, inicialmente
Spring no Desktop

           Spring RCP – Form Builders
FormModelformModel= new DefaultFormModel(newCustomer());
TableFormBuilderbuilder = new TableFormBuilder(formModel);
builder.addSeparator(quot;separator.contactDetailsquot;);
builder.row();
builder.add(quot;namequot;);
builder.row();
builder.add(quot;orgPositionquot;);
builder.row();
builder.add(quot;orgNamequot;);
builder.row();
builder.addSeparator(quot;separator.addressDetailsquot;);
…
builder.add(quot;statequot;);
builder.add(quot;postcodequot;,quot;colSpec=2cmquot;);
builder.row();
builder.add(quot;countryquot;);
JComponentform = builder.getForm();
Spring no Desktop
Remoting

   Sistemas Distribuídos com Spring

• Spring + EJBs

• Spring + RMI

• Spring + JAXRPC (Web Services)

• Spring HTTP Invoker
Spring 2.0

          Novidades do Spring 2.0

• XML mais simples e poderoso (XML Schema)

• Mais uso de Annotations

• Convention over configuration

• Múltiplas linguagens (Java, Groovy, Jruby,
  BeanShell)
Spring Annotation

               Spring Annotation

• Configuração com Annotations

• Integração com JSF

• Brasileiro

http://spring-annotation.dev.java.net/
Livros
Dúvidas?




david@jeebrasil.com.br

www.jeebrasil.com.br
 del.icio.us/davidrvp

More Related Content

What's hot

Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
Stephan Hochdörfer
 
Introduction to Struts
Introduction to StrutsIntroduction to Struts
Introduction to Struts
elliando dias
 
Udi Dahan Intentions And Interfaces
Udi Dahan Intentions And InterfacesUdi Dahan Intentions And Interfaces
Udi Dahan Intentions And Interfaces
deimos
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
Stephan Hochdörfer
 
PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事
longfei.dong
 

What's hot (20)

Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
 
Clean Test Code
Clean Test CodeClean Test Code
Clean Test Code
 
Introduction to Struts
Introduction to StrutsIntroduction to Struts
Introduction to Struts
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Udi Dahan Intentions And Interfaces
Udi Dahan Intentions And InterfacesUdi Dahan Intentions And Interfaces
Udi Dahan Intentions And Interfaces
 
Web前端标准在各浏览器中的实现差异
Web前端标准在各浏览器中的实现差异Web前端标准在各浏览器中的实现差异
Web前端标准在各浏览器中的实现差异
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
 
Database Connection Pane
Database Connection PaneDatabase Connection Pane
Database Connection Pane
 
JavaFX – 10 things I love about you
JavaFX – 10 things I love about youJavaFX – 10 things I love about you
JavaFX – 10 things I love about you
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事PhoneGap:你应该知道的12件事
PhoneGap:你应该知道的12件事
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 

Viewers also liked

RailsConf Europe 2008 Juggernaut Realtime Rails
RailsConf Europe 2008 Juggernaut Realtime RailsRailsConf Europe 2008 Juggernaut Realtime Rails
RailsConf Europe 2008 Juggernaut Realtime Rails
elliando dias
 
Messaging is not just for investment banks!
Messaging is not just for investment banks!Messaging is not just for investment banks!
Messaging is not just for investment banks!
elliando dias
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias
 
Railsmachine - Moonshine
Railsmachine - MoonshineRailsmachine - Moonshine
Railsmachine - Moonshine
elliando dias
 

Viewers also liked (20)

Spring Capitulo 06
Spring Capitulo 06Spring Capitulo 06
Spring Capitulo 06
 
Spring: uma introdução prática
Spring: uma introdução práticaSpring: uma introdução prática
Spring: uma introdução prática
 
J2eetutorial1
J2eetutorial1J2eetutorial1
J2eetutorial1
 
Licenças de software livre
Licenças de software livreLicenças de software livre
Licenças de software livre
 
Conhecendo o Spring
Conhecendo o SpringConhecendo o Spring
Conhecendo o Spring
 
Introdução ao Spring Framework
Introdução ao Spring FrameworkIntrodução ao Spring Framework
Introdução ao Spring Framework
 
domain network services (dns)
 domain network services (dns) domain network services (dns)
domain network services (dns)
 
J2ee architecture
J2ee architectureJ2ee architecture
J2ee architecture
 
J2EE and layered architecture
J2EE and layered architectureJ2EE and layered architecture
J2EE and layered architecture
 
Cluster Computers
Cluster ComputersCluster Computers
Cluster Computers
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and REST
 
RailsConf Europe 2008 Juggernaut Realtime Rails
RailsConf Europe 2008 Juggernaut Realtime RailsRailsConf Europe 2008 Juggernaut Realtime Rails
RailsConf Europe 2008 Juggernaut Realtime Rails
 
Messaging is not just for investment banks!
Messaging is not just for investment banks!Messaging is not just for investment banks!
Messaging is not just for investment banks!
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
シニアの予備校#2
シニアの予備校#2シニアの予備校#2
シニアの予備校#2
 
シニアの予備校 ハローワーク未満 #01
シニアの予備校 ハローワーク未満 #01シニアの予備校 ハローワーク未満 #01
シニアの予備校 ハローワーク未満 #01
 
Railsmachine - Moonshine
Railsmachine - MoonshineRailsmachine - Moonshine
Railsmachine - Moonshine
 
what is soap
what is soapwhat is soap
what is soap
 
Deployment de Rails
Deployment de RailsDeployment de Rails
Deployment de Rails
 
WAC Network APIs @ OverTheAir 2011
WAC Network APIs @ OverTheAir 2011WAC Network APIs @ OverTheAir 2011
WAC Network APIs @ OverTheAir 2011
 

Similar to Uma introdução ao framework Spring

Spring
SpringSpring
Spring
dasgin
 
Strutsjspservlet
Strutsjspservlet Strutsjspservlet
Strutsjspservlet
Sagar Nakul
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
Carles Farré
 

Similar to Uma introdução ao framework Spring (20)

สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1
 
Spring
SpringSpring
Spring
 
Os Johnson
Os JohnsonOs Johnson
Os Johnson
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
JSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph PicklJSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph Pickl
 
Spring and DWR
Spring and DWRSpring and DWR
Spring and DWR
 
Object Oreinted Approach in Coldfusion
Object Oreinted Approach in ColdfusionObject Oreinted Approach in Coldfusion
Object Oreinted Approach in Coldfusion
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Strutsjspservlet
Strutsjspservlet Strutsjspservlet
Strutsjspservlet
 
Strutsjspservlet
Strutsjspservlet Strutsjspservlet
Strutsjspservlet
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Spring overview
Spring overviewSpring overview
Spring overview
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Jsp
JspJsp
Jsp
 
Jsfandsecurity
JsfandsecurityJsfandsecurity
Jsfandsecurity
 

More from elliando dias

Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
elliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
elliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 

More from elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Uma introdução ao framework Spring

  • 1. Java EE Leve Uma introdução ao framework Spring David Ricardo do Vale Pereira david@jeebrasil.com.br
  • 2. O que é Spring? Interface21
  • 3. O que é Spring? • Reduzir a complexidade do desenvolvimento Java EE • Simplificar sem perder o poder • Facilitar o desenvolvimento usando as boas práticas
  • 4. O que é Spring? • Possibilitar que as aplicações sejam construídas com POJOs • Aplicação de serviços aos POJOs de maneira declarativa – Ex: @Transactional
  • 5. O que é Spring? Poder para os POJOs
  • 6. O que é Spring? Spring influenciou... – EJB 3.0 – Java Server Faces
  • 7. O que é Spring? • Container de DI • AOP • Acesso a dados (JDBC, Hibernate, iBatis...) • Gerenciamento de Transações • Agendamento de Tarefas • Mail Support • Remoting • Spring MVC + Spring Web Flow • Spring RCP
  • 8. Injeção de Dependências Inversão de Controle “Inversion of Control (IoC) is a design pattern that addresses a component's dependency resolution, configuration and lifecycle.” (Paul Hammant - PicoContainer)
  • 9. Injeção de Dependências Dependency Lookup x Dependency Injection
  • 10. Injeção de Dependências The Hollywood Principle: Don't call us, we'll call you!
  • 11. Injeção de Dependências Injeção de Dependências Inversion of Control Containers and The Dependency Injection Pattern http://www.martinfowler.com/articles/injection.html Martin Fowler
  • 12. Injeção de Dependências Exemplo depende de Bean 1 Bean 2
  • 13. Injeção de Dependências Sem Inversão de Controle public class Bean1 { private Bean2 bean2; public void metodo() { bean2 = new Bean2(); // sem IoC bean2.usandoBean(); } }
  • 14. Injeção de Dependências Com Dependency Lookup public class Bean1 { private Bean2 bean2; public void metodo() { bean2 = Factory.getBean2(); // Factory (GoF) bean2.usandoBean(); } }
  • 15. Injeção de Dependências Com Dependency Injection public class Bean1 { private Bean2 bean2; public void metodo() { bean2.usandoBean(); } public void setBean2(Bean2 bean2) { this.bean2 = bean2; } }
  • 16. Injeção de Dependências Dois tipos... – Setter Injection – Constructor Injection Spring trabalha com ambos!
  • 17. Injeção de Dependências Setter Injection <bean id=”bean2” class=”pacote.Bean2”/> <bean id=”bean1” class=”pacote.Bean1”> <property name=”bean2”> <ref bean=”bean2”/> </property> </bean>
  • 18. Injeção de Dependências Constructor Injection <bean id=”bean2” class=”pacote.Bean2”/> <bean id=”bean1” class=”pacote.Bean1”> <constructor-arg> <ref bean=”bean2”/> </constructor-arg> </bean>
  • 19. AOP AOP = Aspects Oriented Programming Aspectos
  • 20. AOP 0
  • 21. AOP • Advices – Before Advice – After Advice – Around Advice – Throws Advice – Introduction Advice
  • 22. AOP Um “Hello World!” com AOP public class MessageWriter { public void writeMessage() { System.out.println(“World”); } }
  • 23. AOP public class MessageDecorator implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println(“Hello ”); invocation.proceed(); System.out.println(“!”); return retVal; } }
  • 24. AOP public class HelloWorldAOPExample { public static void main(String args[]) { MessageWriter target = new MessageWriter(); ProxyFactory pf = new ProxyFactory(); pf.addAdvice(new MessageDecorator()); pf.setTarget(target); MessageWriter proxy = (MessageWriter)pf.getProxy(); target.writeMessage(); proxy.writeMessage(); } }
  • 25. Acesso a Dados Acesso a Dados com Spring
  • 26. Acesso a Dados Spring com JDBC • Gerenciamento de DataSources • JDBC Templates • SQLExceptionTranslator
  • 28. Acesso a Dados Gerenciamento de DataSources <bean id=”dataSource” class=”org.springframework.jndi.JndiObjectFactoryBean”> <property name=”jndiName”> <value>java:comp/env/jdbc/meuDataSource</value> </property> </bean> <bean id=”meuDAO” class=”net.java.dev.javarn.dao.MeuDAO”> <property name=”dataSource”> <ref local=”dataSource”/> </property> </bean>
  • 29. Acesso a Dados JDBC Templates • Facilita a execução de consultas • Torna o código mais limpo
  • 30. Acesso a Dados int count = 0; try { PreparedStatement st = getConnection(). prepareStatement(“select count(*) from produto”); ResultSet rs = st.executeQuery(); if (rs.next()) count = rs.getInt(1); } catch(SQLException e) { log.error(e); } finally { try { if (stmt != null) stmt.close(); } catch(SQLException e) { log.warn(e); } try { if (conn != null) conn.close(); } catch(SQLException e) { log.warn(e); } }
  • 31. Acesso a Dados JdbcTemplate jt = new JdbcTemplate(getDataSource()); int count = jt.queryForInt( “select count(*) from produto”);
  • 32. Acesso a Dados <bean id=quot;jdbcTemplatequot; class=quot;org.springframework.jdbc.core.JdbcTemplatequot;> <property name=quot;dataSourcequot;> <ref bean=quot;dataSourcequot;/> </property> </bean> <bean id=quot;studentDaoquot; class=quot;StudentDaoJdbcquot;> <property name=quot;jdbcTemplatequot;> <ref bean=quot;jdbcTemplatequot;/> </property> </bean>
  • 33. Acesso a Dados SQLExceptionTranslator BadSqlGrammarException CannotGetJdbcConnectionException SQLException InvalidResultSetAccessException IncorrectResultSetColumnCountException ...
  • 34. Acesso a Dados Spring com Hibernate • Gerenciamento de Session Factories • Hibernate DAO Support
  • 35. Acesso a Dados Gerenciamento de Session Factories <bean id=”dataSource” ... /> <bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”> <property name=”dataSource”><ref local=”dataSource”/></property> <property name=”hibernateProperties”> <props><prop key=”hibernate.dialect”> org.hibernate.dialect.PostgreSQLDialect </prop></props> </property> <property name=”mappingResources”> <list> <value>Bean1.hbm.xml</value> <value>Bean2.hbm.xml</value> </list> </property> ...
  • 36. Acesso a Dados Hibernate DAO Support public class AlunoDao extends HibernateDaoSupport implements Dao { public Object get(int id) { return getHibernateTemplate().load(Aluno.class, id); } public List getAll() { return getHibernateTemplate().loadAll(Aluno.class); } public void saveOrUpdate(Object o) { getHibernateTemplate().saveOrUpdate(o); } public List findAlunosReprovados() { return getHibernateTemplate().find(“from Aluno a where a.disciplinas.media < ?”, new Object[] { 7 }); } }
  • 37. Acesso a Dados <bean id=quot;sessionFactoryquot; .../> <bean id=quot;daoquot; class=quot;net.java.dev.javarn.TestDaoquot;> <property name=quot;sessionFactoryquot;> <ref bean=quot;sessionFactoryquot; /> </property> </bean>
  • 39. Gerenciamento de Transações @Transactional public interface FooService { Foo getFoo(String fooName); void insertFoo(Foo foo); void updateFoo(Foo foo); }
  • 40. Gerenciamento de Transações public class FooService { public Foo getFoo(String fooName) { ... } @Transactional(propagation = Propagation.REQUIRES_NEW) public void updateFoo(Foo foo) { // ... } }
  • 41. Spring na Web Integração com Frameworks • Spring + Spring MVC • Spring + Java Server Faces • Spring + Webwork • Spring + Tapestry • Spring + Struts
  • 42. Spring na Web Spring Web Flow • Controle de fluxo de aplicações web • Continuations • Problema do botão voltar (back x undo)
  • 43. Spring na Web /step1.do storeForm page1 Controller 1 HTTP Session /step2.do updateForm page2 Controller 2 /lastStep.do Business Service processTx confirmationPage Controller 3
  • 45. Spring na Web • Fluxo como uma máquina de estados • Estados e transições configurados com XML • Atualmente compatível com Spring MVC e Java Server Faces • Suporte a AJAX
  • 46. Spring no Desktop Spring RCP • Rich Client Platform • Programação Desktop com o poder do Spring • Suporte a Swing, inicialmente
  • 47. Spring no Desktop Spring RCP – Form Builders FormModelformModel= new DefaultFormModel(newCustomer()); TableFormBuilderbuilder = new TableFormBuilder(formModel); builder.addSeparator(quot;separator.contactDetailsquot;); builder.row(); builder.add(quot;namequot;); builder.row(); builder.add(quot;orgPositionquot;); builder.row(); builder.add(quot;orgNamequot;); builder.row(); builder.addSeparator(quot;separator.addressDetailsquot;); … builder.add(quot;statequot;); builder.add(quot;postcodequot;,quot;colSpec=2cmquot;); builder.row(); builder.add(quot;countryquot;); JComponentform = builder.getForm();
  • 49. Remoting Sistemas Distribuídos com Spring • Spring + EJBs • Spring + RMI • Spring + JAXRPC (Web Services) • Spring HTTP Invoker
  • 50. Spring 2.0 Novidades do Spring 2.0 • XML mais simples e poderoso (XML Schema) • Mais uso de Annotations • Convention over configuration • Múltiplas linguagens (Java, Groovy, Jruby, BeanShell)
  • 51. Spring Annotation Spring Annotation • Configuração com Annotations • Integração com JSF • Brasileiro http://spring-annotation.dev.java.net/