Meeting 5: Unterschied zwischen den Versionen

Aus Java Student User Group Austria - Java + JVM in Wien Österreich / Vienna Austria
Wechseln zu: Navigation, Suche
(Die Seite wurde neu angelegt: 13. October 08 TODO fotos von dem tag verlinken; generell von jedem treffen welche machen! ==Inversion of Control== Held by Florian M. ==Guice== Held by ? ==Spring=...)
 
K (Schützte „Meeting 5“: Wiederkehrender Vandalismus (‎[edit=autoconfirmed] (unbeschränkt) ‎[move=autoconfirmed] (unbeschränkt)))
 
(31 dazwischenliegende Versionen von 8 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
13. October 08
+
'''When''': Monday, October 13th, 2008 - 19:00
 +
 
 +
'''Where''': [http://www.wegweiser.ac.at/tuwien/hoersaal/F4.html Freihaus HS4]
  
TODO fotos von dem tag verlinken; generell von jedem treffen welche machen!
 
  
 
==Inversion of Control==
 
==Inversion of Control==
Held by Florian M.
+
 
 +
Download the [[Media:JSUG-Inversion of Control-Florian Motlik.pdf|slides]] (pdf, 38KB).<br />
 +
You can also view the [http://www.slideshare.net/javastudentusergroup/jsug-inversion-of-control-by-florian-motlik slides online].
 +
 
 +
===Content===
 +
 
 +
[[Benutzer:Matlock|Florian Motlik]] introduced todays topic IoC, which follows the slogan "''don't call us, we'll call you''". Your code just implements the specific logic but the actual control itself is passed to a certain controller class. A trivial example would be iterating over a collection.
 +
 
 +
 
 +
Instead of writing ...
 +
 
 +
<code>
 +
var someList = [ "Larry", "Curly", "Moe" ];
 +
for(var i = 0; i < someList.length; i++) {
 +
  var name = someList[i];
 +
  println(name.length);
 +
}
 +
</code>
 +
 
 +
... one could just say ...
 +
 
 +
<code>
 +
[ "Larry", "Curly", "Moe" ].each { name | println(name.length)}
 +
</code>
 +
 
 +
... and that's all. By passing a function to a certain method provided by the datastructure itself (make use of closures), the actual iterating over each field is hidden and you don't have to worry about it anymore; your could will be invoked for each item, and therefore control is inverted.
 +
 
 +
 
 +
'''Dependency injection''' (originally introduced by [http://martinfowler.com Martin Fowler]) is a specific form of IoC. Dependencies of a class will be injected for you (constructor/setter/interface/field injections are possible) and therefore the coupling is not necessarily reduced, but its shifted outside the code (in case of Spring into a XML file).
 +
 
 +
===Links===
 +
 
 +
* [http://martinfowler.com/articles/injection.html http://martinfowler.com/articles/injection.html] ... Martin Fowler's article about IoC and DI
 +
* [http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/ http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/] ... Well written article about IoC and DI
  
 
==Guice==
 
==Guice==
Held by ?
 
  
==Spring==
+
Download the [[Media:JSUG-Slides-Google Guice-Jan Zarnikov.pdf|slides]] (pdf, 115KB).<br />
Held by Christoph P.
+
You can also view the [http://www.slideshare.net/javastudentusergroup/jsug-google-guice-by-jan-zarnikov slides online].<br />
 +
Download the [[Media:Jsug-guice-demo-project.zip|sourcecode]] (pdf, 13KB).
 +
 
 +
===Basic facts===
 +
 
 +
Of course theory is nice, but it becomes useful when you start using a concret technology which enables dependency injection for you, such the Google Guice framework presented by [[Benutzer:Comar|Jan Zarnikov]]. It provides a pure Java style (no external XML configuration which makes it possible to misstype a name; refactorings also changes configuration!) with all Java5 features such as generics (type safety) and annotations (injecting is realized via Guice own annotations).
 +
 
 +
===Reductio ad absurdum===
 +
 
 +
The following application is so simple, it actually does not require guice to work, but just for the sake for an introduction example:
 +
<source lang="java">
 +
public class MyApplication {
 +
  public static void main(String[] args) {
 +
    Injector injector = Guice.createInjector();
 +
    Greeter greeter = injector.getInstance(Greeter.class);
 +
    greeter.sayHello();
 +
  }
 +
}
 +
 
 +
public class Greeter {
 +
  void sayHello() {
 +
    System.out.println("Hello, world!");
 +
  }
 +
}
 +
</source>
 +
 
 +
Taken from the presentation: [http://www.youtube.com/watch?v=8RGhT-YySDY http://www.youtube.com/watch?v=8RGhT-YySDY]
 +
 
 +
===Simple example===
 +
 
 +
The following chapter shows a simple application with a database connection and a mocked connection for its unit tests:
 +
<br /><br />
 +
[[Bild:Guice-Simple example.png|Guice Example]]
 +
 
 +
The <code>UserController</code> class is subject of the JUnit test and requires a database (in fact, just something that implements the <code>DAO</code> interface). Because unit tests should only test a certain unit (and not the database management system or anything else), the controller class will get another implementation of <code>DAO</code> injected if it is run by JUnit (namely <code>TestDAO</code> instead of <code>JdbcDAO</code>).
 +
 
 +
 
 +
Injecting objects is just as easy as annotating the constructor with the <code>@Inject</code> annotation (you could also have used it at the field itself, or provided a setter method):
 +
<source lang="java">
 +
public class UserController {
 +
 
 +
  private final DAO dao;
 +
 
 +
  @Inject
 +
  public UserController(DAO dao) {
 +
    this.dao = dao;
 +
  }
 +
 
 +
  public boolean login(String username, String password) {
 +
    List<User> users = this.dao.getUsers();
 +
    // ...
 +
  }
 +
}
 +
</source>
 +
 
 +
 
 +
Of course you also have to configure your dependencies somewhere:
 +
<source lang="java">
 +
public class AppModule extends AbstractModule {
 +
  public void configure() {
 +
    bind(DAO.class).to(JdbcDAO.class);
 +
  }
 +
}
 +
 
 +
public class TestModule extends AbstractModule {
 +
  public void configure() {
 +
    bind(DAO.class).to(TestDAO.class);
 +
  }
 +
}
 +
</source>
 +
 
 +
 
 +
To startup the Guice framework, you have to do following first:
 +
<source lang="java">
 +
public class MyApplication {
 +
  public static void main(String[] args) {
 +
    // configure Guice with AppModule
 +
    Injector injector = Guice.createInjector(new AppModule());
 +
 
 +
    // userController already got its proper DAO instance injected
 +
    UserController userController = injector.getInstance(UserController.class);
 +
 
 +
    boolean isLoggedIn = userController.login("Foo", "Bar");
 +
  }
 +
}
 +
</source>
 +
 
 +
 
 +
Or use your special configuration for unit test:
 +
<source lang="java">
 +
public class UserControllerTest {
 +
 
 +
  private UserController userController;
 +
 
 +
  @Before
 +
  public void setup() {
 +
    // configure Guice with TestModule, instead with AppModule
 +
    Injector injector = Guice.createInjector(new TestModule());
 +
    this.userController = injector.getInstance(UserController.class);
 +
´ }
 +
 
 +
  // some tests...
 +
 
 +
}
 +
</source>
 +
 
 +
===Links===
 +
 
 +
* [http://code.google.com/p/google-guice/ http://code.google.com/p/google-guice/] ... Official Guice website
 +
* [http://docs.google.com/View?docid=dd2fhx4z_5df5hw8 http://docs.google.com/View?docid=dd2fhx4z_5df5hw8] ... Official userguide
 +
* [http://crazybob.org/2007/06/introduction-to-guice-video-redux.html http://crazybob.org/2007/06/introduction-to-guice-video-redux.html] ... Presentation about Guice
 +
* [http://www.youtube.com/watch?v=FFXhXZnmEQM http://www.youtube.com/watch?v=FFXhXZnmEQM] ... Other presentation about Guice
 +
 
 +
== Springframework ==
 +
 
 +
Download the [[Media:JSUG-Slides_Spring_Christoph_Pickl.pdf|slides]] (pdf, 0.6MB).<br />
 +
You can also view the [http://www.slideshare.net/javastudentusergroup/jsug-spring-by-christoph-pickl slides online].
 +
 
 +
===Agenda===
 +
 
 +
# Short introduction to the Springframework
 +
# Basic declaration of beans
 +
# Medieval times (evolution of Spring)
 +
# Advanced features (just a preview)
 +
# Demo
 +
 
 +
===Content===
 +
Spring should be part of every Java application today; at least so says the lecturer [[Benutzer:Christoph.pickl|Christoph Pickl]]. If it is not Spring, it should be any other framework which enables dependency injection. Spring ...
 +
 
 +
* ''... is a leightweight inversion of control and aspect oriented container framework.''
 +
* ''... makes developing JEE applications easier and more fun!''
 +
 
 +
 
 +
Spring's mission statements are:
 +
 
 +
* JEE should be easier to use.
 +
* It is best to program to interfaces, rather than classes [...]
 +
* JavaBeans offer a great way of configuring applications.
 +
* OO is more important than any implementation technology [...]
 +
* Checked exceptions are overused in Java [...]
 +
* Testability is essential [...]
 +
 
 +
 
 +
Each and every bean declarations got a <code>beans</code> root node declaring some namespaces:
 +
<source lang="xml">
 +
<?xml version="1.0" encoding="UTF-8"?>
 +
<!-- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 +
    "http://www.springframework.org/dtd/spring-beans.dtd"> -->
 +
<beans
 +
  xmlns="http://www.springframework.org/schema/beans"
 +
  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-2.0.xsd"
 +
>
 +
 
 +
  <!-- define your beans here -->
 +
 
 +
</beans>
 +
</source>
 +
 
 +
 
 +
One could, for example, define a single dao-instance, and reuse that instance by injecting it into different controller classes:
 +
<source lang="xml">
 +
<!-- this is our first (singleton) bean -->
 +
<bean id="myDao" class="jsug.MyDao" />
 +
 
 +
<bean id="myCtrl1" class="jsug.MyController1">
 +
  <!-- invokes MyController1.setDao(MyDao) -->
 +
  <property name="dao">
 +
    <ref bean="myDao" />
 +
  </property>
 +
</bean>
 +
 
 +
<!-- share same dao in second controller -->
 +
<bean id="myCtrl2" class="jsug.MyController2">
 +
  <property name="dao">
 +
    <ref bean="myDao" />
 +
  </property>
 +
</bean>
 +
</source>
 +
 
 +
 
 +
Using the springframework today is very non-intrusive. Just load your application context and that's it:
 +
<source lang="java">
 +
// single code dependency to spring throughout our whole application
 +
import org.springframework.context.support.ClassPathXmlApplicationContext;
 +
 
 +
public class App {
 +
  public static void main(String[] args) {
 +
    String[] beanDefinitions = { "/beans.xml" };
 +
    new ClassPathXmlApplicationContext(beanDefinitions);
 +
  }
 +
 
 +
  public App() {
 +
    // spring will invoke this constructor for us
 +
  }
 +
 
 +
  public void init() {
 +
    // and spring will also invoke this initialize method for us
 +
  }
 +
}
 +
</source>
 +
 
 +
 
 +
Sometimes, your beans have to be initialized via a certain method. To do this, declare your bean as follows:
 +
<source lang="xml">
 +
<bean id="myBean" class="jsug.MyBean" init-method="init">
 +
  <constructor-arg index="0" value="someStringValue" />
 +
  <constructor-arg index="1" ref="someOtherBean" />
 +
  <property name="firstName" value="Christoph" />
 +
</bean>
 +
</source>
 +
 
 +
The corresponding class:
 +
<source lang="java">
 +
public class MyBean {
 +
 
 +
  private final String someString;
 +
  private String firstName;
 +
 
 +
  // #1 first of all, the bean will be created with proper constructor args
 +
  public MyBean(String someString, Bean b) {
 +
    this.someString = someString;
 +
  }
 +
 
 +
  // #2 afterwards, all properties will be set via setter methods
 +
  public void setFirstName(String firstName) {
 +
    this.firstName = firstName;
 +
  }
 +
 
 +
  // #3 finally, the initialize method will get invoked
 +
  public void init() {
 +
    // initialize bean in here
 +
  }
 +
}
 +
</source>
 +
 
 +
=== Links ===
 +
* [http://www.springframework.org http://www.springframework.org] ... Official Website
 +
* [http://parleys.com/display/PARLEYS/Home#talk=18612266;slide=1;title=Comparing%20Dependency%20Injection%20Frameworks http://parleys.com/display/...Injection%20Frameworks] ... Short presentation "Comparing Dependency Injection Frameworks"
 +
 
 +
==Gallery==
 +
<gallery>
 +
Bild:Meeting5 picture1.jpg|Sun representative Ivan and Florian Motlik
 +
Bild:Meeting5 picture2.jpg|Christoph Pickl talking about Spring's mission statement
 +
Bild:Meeting5 picture3.jpg|The excited crowd
 +
</gallery>
 +
 
 +
Thanks to Jan for providing these pictures.
  
==Socializing==
+
[[Category:Meeting]]
Afterwards, we met in a nearby pub for a drink (or more) and had a nice discussion. Also, one of Sun Microsystem's representator joined us there.
 

Aktuelle Version vom 18. März 2013, 07:51 Uhr

When: Monday, October 13th, 2008 - 19:00

Where: Freihaus HS4


Inversion of Control

Download the slides (pdf, 38KB).
You can also view the slides online.

Content

Florian Motlik introduced todays topic IoC, which follows the slogan "don't call us, we'll call you". Your code just implements the specific logic but the actual control itself is passed to a certain controller class. A trivial example would be iterating over a collection.


Instead of writing ...

var someList = [ "Larry", "Curly", "Moe" ];
for(var i = 0; i < someList.length; i++) {
  var name = someList[i];
  println(name.length);
}

... one could just say ...

[ "Larry", "Curly", "Moe" ].each { name | println(name.length)}

... and that's all. By passing a function to a certain method provided by the datastructure itself (make use of closures), the actual iterating over each field is hidden and you don't have to worry about it anymore; your could will be invoked for each item, and therefore control is inverted.


Dependency injection (originally introduced by Martin Fowler) is a specific form of IoC. Dependencies of a class will be injected for you (constructor/setter/interface/field injections are possible) and therefore the coupling is not necessarily reduced, but its shifted outside the code (in case of Spring into a XML file).

Links

Guice

Download the slides (pdf, 115KB).
You can also view the slides online.
Download the sourcecode (pdf, 13KB).

Basic facts

Of course theory is nice, but it becomes useful when you start using a concret technology which enables dependency injection for you, such the Google Guice framework presented by Jan Zarnikov. It provides a pure Java style (no external XML configuration which makes it possible to misstype a name; refactorings also changes configuration!) with all Java5 features such as generics (type safety) and annotations (injecting is realized via Guice own annotations).

Reductio ad absurdum

The following application is so simple, it actually does not require guice to work, but just for the sake for an introduction example: <source lang="java"> public class MyApplication {

 public static void main(String[] args) {
   Injector injector = Guice.createInjector();
   Greeter greeter = injector.getInstance(Greeter.class);
   greeter.sayHello();
 }

}

public class Greeter {

 void sayHello() {
   System.out.println("Hello, world!");
 }

} </source>

Taken from the presentation: http://www.youtube.com/watch?v=8RGhT-YySDY

Simple example

The following chapter shows a simple application with a database connection and a mocked connection for its unit tests:

Guice Example

The UserController class is subject of the JUnit test and requires a database (in fact, just something that implements the DAO interface). Because unit tests should only test a certain unit (and not the database management system or anything else), the controller class will get another implementation of DAO injected if it is run by JUnit (namely TestDAO instead of JdbcDAO).


Injecting objects is just as easy as annotating the constructor with the @Inject annotation (you could also have used it at the field itself, or provided a setter method): <source lang="java"> public class UserController {

 private final DAO dao;
 @Inject
 public UserController(DAO dao) {
   this.dao = dao;
 }
 public boolean login(String username, String password) {
   List<User> users = this.dao.getUsers();
   // ...
 }

} </source>


Of course you also have to configure your dependencies somewhere: <source lang="java"> public class AppModule extends AbstractModule {

 public void configure() {
   bind(DAO.class).to(JdbcDAO.class);
 }

}

public class TestModule extends AbstractModule {

 public void configure() {
   bind(DAO.class).to(TestDAO.class);
 }

} </source>


To startup the Guice framework, you have to do following first: <source lang="java"> public class MyApplication {

 public static void main(String[] args) {
   // configure Guice with AppModule
   Injector injector = Guice.createInjector(new AppModule());
   // userController already got its proper DAO instance injected
   UserController userController = injector.getInstance(UserController.class);
   boolean isLoggedIn = userController.login("Foo", "Bar");
 }

} </source>


Or use your special configuration for unit test: <source lang="java"> public class UserControllerTest {

 private UserController userController;
 @Before
 public void setup() {
   // configure Guice with TestModule, instead with AppModule
   Injector injector = Guice.createInjector(new TestModule());
   this.userController = injector.getInstance(UserController.class);

´ }

 // some tests...

} </source>

Links

Springframework

Download the slides (pdf, 0.6MB).
You can also view the slides online.

Agenda

  1. Short introduction to the Springframework
  2. Basic declaration of beans
  3. Medieval times (evolution of Spring)
  4. Advanced features (just a preview)
  5. Demo

Content

Spring should be part of every Java application today; at least so says the lecturer Christoph Pickl. If it is not Spring, it should be any other framework which enables dependency injection. Spring ...

  • ... is a leightweight inversion of control and aspect oriented container framework.
  • ... makes developing JEE applications easier and more fun!


Spring's mission statements are:

  • JEE should be easier to use.
  • It is best to program to interfaces, rather than classes [...]
  • JavaBeans offer a great way of configuring applications.
  • OO is more important than any implementation technology [...]
  • Checked exceptions are overused in Java [...]
  • Testability is essential [...]


Each and every bean declarations got a beans root node declaring some namespaces: <source lang="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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"

>


</beans> </source>


One could, for example, define a single dao-instance, and reuse that instance by injecting it into different controller classes: <source lang="xml"> <bean id="myDao" class="jsug.MyDao" />

<bean id="myCtrl1" class="jsug.MyController1">

 <property name="dao">
   <ref bean="myDao" />
 </property>

</bean>

<bean id="myCtrl2" class="jsug.MyController2">

 <property name="dao">
   <ref bean="myDao" />
 </property>

</bean> </source>


Using the springframework today is very non-intrusive. Just load your application context and that's it: <source lang="java"> // single code dependency to spring throughout our whole application import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

 public static void main(String[] args) {
   String[] beanDefinitions = { "/beans.xml" };
   new ClassPathXmlApplicationContext(beanDefinitions);
 }
 public App() {
   // spring will invoke this constructor for us
 }
 public void init() {
   // and spring will also invoke this initialize method for us
 }

} </source>


Sometimes, your beans have to be initialized via a certain method. To do this, declare your bean as follows: <source lang="xml"> <bean id="myBean" class="jsug.MyBean" init-method="init">

 <constructor-arg index="0" value="someStringValue" />
 <constructor-arg index="1" ref="someOtherBean" />
 <property name="firstName" value="Christoph" />

</bean> </source>

The corresponding class: <source lang="java"> public class MyBean {

 private final String someString;
 private String firstName;
 
 // #1 first of all, the bean will be created with proper constructor args
 public MyBean(String someString, Bean b) {
   this.someString = someString;
 }
 
 // #2 afterwards, all properties will be set via setter methods
 public void setFirstName(String firstName) {
   this.firstName = firstName;
 }
 
 // #3 finally, the initialize method will get invoked
 public void init() {
   // initialize bean in here
 }

} </source>

Links

Gallery

Thanks to Jan for providing these pictures.