Contenu connexe
Similaire à 2009 03 17 Spring101 (20)
2009 03 17 Spring101
- 30. Reportgenerator (3) Schritt 1: Führe Container ein (cont‘d) public class Container { public static Container instance ; private Map<String, Object> components ; public Container() { components = new HashMap<String, Object>(); instance = this ; components .put( "reportGenerator" , new PdfReportGenerator()); components .put( "reportService" , new ReportService()); } public Object getComponent(String id) { return components .get(id); } }
- 32. Reportgenerator (5) Schritt 2: Verwende Service-Locator Pattern (cont‘d) public class ServiceLocator { private static Container container = Container. instance ; public static ReportGenerator getReportGenerator() { return (ReportGenerator) container .getComponent( "reportGenerator" ); } } public class ReportService { private ReportGenerator reportGenerator = ServiceLocator. getReportGenerator (); // Rest weggelassen }
- 34. Reportgenerator (7) Schritt 3: Realisiere DI via Reflection (cont‘d) public class Container { // Ausschnitt! private void processEntry(String key, String value) throws Exception { String[] parts = key.split( "." ); if (parts. length == 1) { // erzeuge Komponente Object component = Class. forName (value).newInstance(); components .put(parts[0], component); } else { // injiziere Dependency Object component = components .get(parts[0]); Object reference = components .get(value); PropertyUtils. setProperty (component, parts[1], reference); } } }
- 37. Reportgenerator (10) Schritt 4: Konfiguration mit Spring Beans (cont‘d) import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml" ); ReportService reportService = (ReportService) context.getBean( "reportService" ); reportService.generateAnnualReport(2008); } }
- 38. Reportgenerator (10) Schritt 4: Konfiguration mit Spring Beans (cont‘d) <? 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.xsd" > < bean id = "defaultGenerator" class = "de.dlr.spring101.report.step04.PdfReportGenerator" /> < bean id = "reportService" class = "de.dlr.spring101.report.step04.ReportService" > < property name = "reportGenerator" > < ref local = "defaultGenerator" /> </ property > </ bean > </ beans >