Spring的Io C容器

download Spring的Io C容器

If you can't read please download the document

Transcript of Spring的Io C容器

  • 1. Dont call us, we will call you. Spring

2. China-Pub InfoQ InfoQ InfoQ InfoQ http://infoq.com/cn/minibooks/spring-ioc 3. Spring IoC Spring....................................................................................................................11.1 Spring ..............................................................................................................................11.2 Spring ..........................................................................................................................21.3 Spring ..............................................................................................................................41.4 .............................................................................................................................................7IoC.........................................................................................................................82.1 .............................................................................................82.2 ................................................................................................... 112.2.1 ................................................................................................................ 112.2.2 setter ............................................................................................................... 112.2.3 ........................................................................................................................122.2.4 ....................................................................................................132.3 IoC.............................................................................................................................132.4 ...........................................................................................................................................15IoC Service Provider .........................................................................................163.1 IoC Service Provider .....................................................................................................163.2 IoC Service Provider...........................173.2.1 ................................................................................................................173.2.2 ................................................................................................................183.2.3 ....................................................................................................................193.3 ...........................................................................................................................................19SpringIoCBeanFactory .......................................................................................204.1 BeanFactory ..............................................................................................224.2 BeanFactory ..........................................................................244.2.1 ................................................................................................................244.2.2 ........................................................................................................264.2.3 ........................................................................................................................294.3 BeanFactoryXML .....................................................................................................314.3.1 ..........................................................................................................314.3.2 ............................................................................................................334.3.3 Help Me, Help You.........................................................................................................344.3.4 ............................................................................................................484.3.5 beanscope ...................................................................................................................494.3.6 FactoryBean................................................................................................544.3.7 ................................................................................................................594.4 .......................................................................................................................64 4. Spring IoC 4.4.1 .................................................................................................................654.4.2 .........................................................................................................664.4.3 bean.............................................................................................................734.5 ...........................................................................................................................................83Spring IoCApplicationContext............................................................................. 8425.1 ...................................................................................................................845.1.1 SpringResource.......................................................................................................8535.1.2 ResourceLoaderURL...............................................................................865.1.3 ApplicationContextResourceLoader...........................................................................89 45.2 I18n MessageSource ..............................................................................955.2.1 Java SE............................................................................................955.2.2 MessageSourceApplicationContext ............................................................................9655.3 .................................................................................................................1005.3.1 ..........................................................................................................1005.3.2 Spring ........................................................................103 65.3.3 Spring....................................................................................1045.4 .........................................................................................................10775.5 .........................................................................................................................................108Spring IoC.................................................................................................... 10986.1 Spring 2.5 ........................................................................................1096.1.1 @Autowired..........................................................................10996.1.2 @AutowiredJSR250 .................................1136.1.3 classpath-scanning.....................................1146.2 Spring 3.0 ........................................................................................................................117 106.3 .........................................................................................................................................118 111213141516 17 5. [email protected]/[email protected] 6. 1.1 Spring 11 2 Spring 3 45 Spring Spring Spring 6 J2EE 7 J2EE J2EEJ2EE 8 Spring2003JavaRod JohnsonExpert One-On-One J2EE Development and DesignJava EE EJB Spring9 1.1 Spring 10 /11 12 13 ITIBM 14 15 16 EJB1.x2.xEJBEJB3SpringPOJO 17 7. 2Spring IoC J2EE EJB J2EE EJB EJBJ2EE EJB J2EE EJBJ2EE EJBEJB ContainerJ2EE Application Server BEAWebLogicIBMWebSphere JBossEJB Container WebLogicWebSphere EJB EJB EJB EJBEJB EJB EJB EJBJ2EE J2EEEJB SpringSpring EJBJ2EE SpringJ2EE SpringEJBEJB EJB Spring Java 1.2 Spring 8. 1.2 Spring 3EJB EJB SpringPOJOPlain Old Java ObjectJava 2 POJO POJOSpring3 POJOPOJOSpring1.x2.02.5 POJOJavaSpring 4 POJOSpring1-1 5 ORM HibernateiBATISJPA6DAO ToplinkWebSpring JDBC JDOJEE Spring MVC JMXSpring Portlet MVC 7 JMS JCA Web EJB AOPSpring AOP Remoting8 JavaMailAspectJ9Core 10 IoC Framework 111213 1-1 Spring Spring 14 1-1 SpringSpring SpringSpringCoreSpring15 IoCIoC Container SpringIoCSpringCore16 SpringIO 17 9. 4Spring IoC SpringAOPAOPAOPPOJOOOP/OOSDSpringAOP AOP AllianceProxyIoCSpring AOPSpringIoCSpring AOP SpringCoreAOP SpringJDBC APIAPI SpringORMHibernateiBATISToplink JPASpringSpring AOP Spring AOP Java EEJNDIJMSJavaMailSpring Java EESpringJava EE Java EESpring SpringPOJO SpringRemoting SpringRemotingSpringJava EE WebSpringWeb MVCSpringWeb MVCWeb MVCSpringPortlet MVCSpring Web MVCSpring Web MVC Spring Web MVCWebStrutsWebWorkJSFSpringWebWebViewSpring Web Spring SpringSpring SpringSpring SpringIoCSpringAOPSpringSpringJava EEJavaJavaJ2SEJ2EEJ2MESpringSpringSpringSpring 1.3Spring 1995Java10 10. 1.3 Spring 5Spring SpringSpring SpringSpring 2 Spring Web FlowSWF Spring Web FlowSpring Web MVCWebSpring Web Flow 3Spring Web MVCWebSpring Web FlowAjaxJSF4 Spring Web Services Spring Web ServicesContract-FirstDocument-drivenWebWebWeb5XMLSpringSpringSecurityWeb Spring SecurityAcegi Security Spring SecurityAcegi Security6SpringSpring Security 2.0Acegi Security 1.0RESTful7Spring Web FlowSpring Web ServicesSpring 8 Spring Dynamic Modules for OSGi Service Platforms Spring-DMSpringOSGiSpringOSGiSpringSource Application9PlatformSpring-DMSpring-DM10 Spring Batch Spring BatchSpringSpringSource11AccentureSpring Batch Spring Integration Spring IntegrationSpringEnterprise 12IntegrationEnterprise Integration Patterns Spring13 Spring LDAP Spring LDAPSpring Template Method Pattern)14 http://www.springframework.org/webflow http://www.springframework.org/spring-ws 15 http://static.springframework.org/spring-security/site/index.html http://www.springframework.org/osgi http://www.springframework.org/spring-batch16 http://www.springframework.org/spring-integration http://www.eaipatterns.com/ http://www.springframework.org/ldap17 11. 6Spring IoC LdapTemplateLDAP Spring IDE EclipseSpringSpring IDE Spring IDEEclipse EclipseSpring Spring Modules SpringSpring Spring ModulesSpring Spring Spring ModulesANTOSWorkflow Apache OJBiBatis Spring JavaConfig SpringXML Spring 2.5Spring JavaConfigSpring Spring 2.5 Spring Rich Client Eclipse RCPSWT/JFaceGUI SpringSwingGUI Spring Rich Client SwingSpringSpring Rich Client Spring .NET SpringJava.NET Spring .NETSpringSource.NET Spring BeanDoc Spring BeanDocSpring SpringApache Lisence Version 2.0Spring ProjectsSpring Projects SpringSource Interface21Spring Spring ProjectsSpring Portfolio SpringSourceSpring PortfolioSpring PortfolioSpring ProjectsAspectJSpring Spring Framework http://springide.org/ https://springmodules.dev.Java.net/ http://www.springframework.org/Javaconfig http://www.springframework.org/spring-rcp http://www.springframework.net/ http://spring-beandoc.sourceforge.net/ PortfolioSpring 12. 1.4 7Spring SecurityAcegi Spring Web Flow Spring Web Services Spring Dynamic Modules for the OSGi Service Platform 2 Spring Batch Pitchforkhttp://www.springsource.com/pitchfork)3 AspectJhttp://www.eclipse.org/aspectj/) Spring IDE Spring .NET4 Spring LDAP Spring Rich Client 5 Spring IntegrationSpring PortfolioSpringSource6 SpringJavaSpringSource Spring Dynamic ModulesJava SpringSource Application PlatformSpringSource Enterprise 7 SpringSource Apache HTTPD Apache Tomcat Apache ActiveMQ 8Spring SpringSpring Spring9 SpringDonald J. TrumpHow To Get Rich Before the dream lifts you into the clouds, make sure look hard at the facts on the ground. 10SpringSpringSpring Spring11 Spring1.4 12 SpringSpring Spring13 Spring Spring14 15 http://www.covalent.net/supportservices/apache/index.html16 http://www.covalent.net/supportservices/tomcat/index.html http://www.covalent.net/supportservices/activemq/index.html 17 13. 8 Spring IoC 2IoC IoC 2.1 IoCLightweight Container) Inversion of Control Dependency InjectionDont call us, we will call you. IoCIoCIoC IoC IoCExpert Spring MVC and Web FlowExpert One-on-One J2EE without EJBIoCIoCIoCIoC FX FX FXNewsProvider2-12-1FXNewsProvider public class FXNewsProvider { FXForeign ExchangeFX 14. 2.1 9 private IFXNewsListener newsListener;private IFXNewsPersister newPersistener;public void getAndPersistNews(){String[] newsIds = newsListener.getAvailableNewsIds();if(ArrayUtils.isEmpty(newsIds)) 2{ return;} 3for(String newsId : newsIds){FXNewsBean newsBean = newsListener.getNewsByPK(newsId); 4newPersistener.persistNews(newsBean);newsListener.postProcessIfNecessary(newsId);}} 5} FXNewsProvider IFXNewsListener IFXNews-6 Persister Dow JonesDowJonesNewsLis- tenerDowJonesNewsPersisterIFXNewsProvider7 2-28 2-2IFXNewsProviderpublic FXNewsProvider() 9{ newsListener = new DowJonesNewsListener(); newPersistener = new DowJonesNewsPersister();} 10 11 new Service-12 Locator 13 14 FXNewsProvider getAndPersistNews()newsListenernewsListener 15 IoC16 J2EE17 15. 10Spring IoC IoC 2-1IoC Service Provider 2-1 IoC IoCIoC Service ProviderIoC Service Provider IoC Service Provider IoC Service ProviderIoC Service ProviderIoC IoC Service Provider IoC 2-2IoC2-2 IoC Honey IoCIoC IoC 16. 2.2 11 2.2 IoC Service Provider2 3 Waiter,Tsingdao, please. 4 IoCIoC Service Provider5IoC Martin FowlerInversion of Control Containers and the Dependency Injection patternconstructor6 injectionsettersetter injectioninterface injection 7 2.2.1 8 IoCFXNewsProvider 2-39 2-3FXNewsProvider public FXNewsProvider(IFXNewsListener newsListner,IFXNewsPersister newsPersister) {10this.newsListener = newsListner;this.newPersistener = newsPersister; }11 IoC Service Provider 12 IoC Service Provider 13 2.2.2 setter 14 JavaBeansetXXX()getXXX()setXXX() settergetXXX()gettersetter15 gettersetter setterFXNewsProvider setter2-4 16 2-4setterFXNewsProvider public class FXNewsProvider17 17. 12Spring IoC {private IFXNewsListener newsListener;private IFXNewsPersister newPersistener; public IFXNewsListener getNewsListener() {return newsListener;}public void setNewsListener(IFXNewsListener newsListener) {this.newsListener = newsListener;}public IFXNewsPersister getNewPersistener() {return newPersistener;}public void setNewPersistener(IFXNewsPersister newPersistener) {this.newPersistener = newPersistener;}}setNewsListenersetNewPersistenerFXNewsProvider setter 2.2.3 IoC Service Provider IoC Service Provider2-3 FXNewsProvider FXNewsProviderIoC Service ProviderIFXNewsListener IFXNewsListenerCallableinjectNewsListner InjectionServiceContainerIoC Service ProviderFXNewsProvider 2-3 FXNewsProvider 18. 2.3 IoC 13 Avalon 2 2-43 45 2-4 6 2.2.4 7 setter8 9 Java 10 settersetter 11 setterIDE 12 setter 13 2.3 IoC IoC 14 IoC IoC 15 IoC FXNewsProviderIoC 16 17 19. 14 Spring IoC MarketWin24MarketWin24 MarketWin24NewsListener DowJonesNewsPersister FXNewsProviderIoCDowJonesNewsListener FXNewsProviderMarketWin24NewsProvider IoCFXNewsProvider DowJonesMarketWin24 MarketWin24 MarketWin24FXNewsProviderMarketWin24NewsListener 2-52-5IoCFXNewsProviderFXNewsProvider dowJonesNewsProvider = new FXNewsProvider(new DowJonesNewsListener(),new DowJonesNewsPersister());...FXNewsPrivider marketWin24NewsProvider = new FXNewsProvider(new MarketWin24NewsListener(),new DowJonesNewsPersister());...IoC FXNewsProvider FXNewsProviderIFXNewsListener TDDTest Driven Developement IoCIoC FXNewsProviderMockNewsListenerFXNewsProvider DowJonesNewsListener 2-62-6FXNewsProvider MockNewsListner public class MockNewsListener implements IFXNewsListener {public String[] getAvailableNewsIds() {throw new FXNewsRetrieveFailureException();}public FXNewsBean getNewsByPK(String newsId) {// TODOreturn null;}public void postProcessIfNecessary(String newsId) {// TODO} } FXNewsProvider 20. 2.4 15public class FXNewsProviderTest extends TestCase {private FXNewsProvider newsProvider;@Override protected void setUp() throws Exception {2 super.setUp(); newsProvider = new FXNewsProvider(new MockNewsListener(),new MockNewsPersister()); } @Override3 protected void tearDown() throws Exception { super.tearDown(); newsProvider = null; 4 } public void testGetAndPersistNewsWithoutResourceAvailable() {5 try {newsProvider.getAndPersistNews();fail("Since MockNewsListener has no news support, 6we should fail to get above."); } catch(FXNewsRetrieveFailureException e)7 {// }8 } }IoC9 IoCIoC10 2.4 11 IoC IoCIoC12 IoCIoC Service Provider13 14 15 16 17 21. 16 Spring IoC 3 IoC Service Provider IoC Service Provider IoC Service Provider IoC IoC Service ProviderIoCIoC Service ProviderIoC IoC IoC3-1 3-1FXNewsProvider IFXNewsListener newsListener = new DowJonesNewsListener(); IFXNewsPersister newsPersister = new DowJonesNewsPersister(); FXNewsProvider newsProvider = new FXNewsProvider(newsListener,newsPersister); newsProvider.getAndPersistNews();IoC Service Provider Spring IoCIoC Service Provider3.1IoC Service Provider IoC Service Provider IoCIoC Service Provider IoC Service Provider NullPointerException IoC ServiceProvider ABABAService 22. 3.2 IoC Service Provider 17 3.2 IoC Service Provider 2 IoC Service Provider 3 IoC Service Provider 4 5 6 IoC Service Provider IoC Service Provider 7 8 XML 9 IoC Service Provider 10 IoC Service Provider 11 3.2.1 12 IoCPicoContainer SpringAvalon 13 3-2 3-2 14 IoContainer container = ...; container.register(FXNewsProvider.class,new FXNewsProvider()); container.register(IFXNewsListener.class,new DowJonesNewsListener()); ... 15 FXNewsProvider newsProvider = (FXNewsProvider)container.get(FXNewsProvider.class); newProvider.getAndPersistNews(); IoC 16 www.picocontainer.org 17 23. 18 Spring IoC 3-3 3-3 IoContainer container = ...; container.register(FXNewsProvider.class,new FXNewsProvider()); container.register(IFXNewsListener.class,new DowJonesNewsListener()); ... container.bind(IFXNewsListenerCallable.class, container.get(IFXNewsListener.class)); ... FXNewsProvider newsProvider = (FXNewsProvider)container.get(FXNewsProvider.class); newProvider.getAndPersistNews();bindIFXNewsListenerCallable IFXNewsListenerFXNewsProvider IFXNewsListener FXNewsProviderFXNewsProvider IoC Service ProviderIoC 3.2.2 propertiesXML XML Spring IoCPicoContainerNanoContainerXML FXNewsProviderSpring 3-4 3-4SpringFXNewsProvider 3-5newsProvider FXNewsProvider 3-5FXNewsProvider ... container.readConfigurationFiles(...); FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("newsProvider"); newsProvider.getAndPersistNews(); 24. 3.3 193.2.3 Google GuiceBob LeeJava 5Generic IoCGuice2 3-6Guice FXNewsProvider3 3-6GuiceFXNewsProvider public class FXNewsProvider {private IFXNewsListener newsListener; 4private IFXNewsPersister newPersistener;@Injectpublic FXNewsProvider(IFXNewsListener listener,IFXNewsPersister persister){5this.newsListener = listener;this.newPersistener = persister;} 6... }@InjectIoC Service ProviderFXNewsProvider 7 GuiceModule3-7 FXNewsProviderModule8 3-7FXNewsProviderModule public class NewsBindingModule extends AbstractModule {9@Overrideprotected void configure() {bind(IFXNewsListener.class) .to(DowJonesNewsListener.class).in(Scopes.SINGLETON); 10bind(IFXNewsPersister.class) .to(DowJonesNewsPersister.class).in(Scopes.SINGLETON);}} 11 ModuleGuice 3-8 12 3-8GuiceFXNewsProvider Injector injector = Guice.createInjector(new NewsBindingModule()); 13 FXNewsProvider newsProvider = injector.getInstance(FXNewsProvider.class); newsProvider.getAndPersistNews(); 14 3.3 15 IoCIoC Service ProviderIoC Service16 Provider IoC Service Provider IoC Service ProviderSpringIoC 17 25. 20Spring IoC SpringIoCBeanFactory 4 BeanFactory BeanFactory BeanFactoryXML SpringIoCIoC Service ProviderIoC SpringIoCIoC IoCIoCSpringIoCSpring AOPSpringIoCIoC Service Provider 4-1 4-1 SpringIoCIoC Service Provider SpringIoCIoCIoC SpringBeanFactoryApplicationContext BeanFactoryIoCIoC 4 SpringIoCBeanFactorylazy-loadBeanFactoryIoC ApplicationContextApplicationContextBeanFactoryBeanFactoryApplicationContext 26. 3.3 21ApplicationContext BeanFactory ApplicationContext BeanFactory 2 ApplicationContext 4-2BeanFactoryApplicationContext 34567 4-2 BeanFactoryApplicationContext8 ApplicationContextBeanFactoryBeanFactory IoCApplicationContext 5 9 BeanFactoryApplica- tionContext10BeanFactoryBean SpringPOJOJavaBean 11 SpringIoCSpringIoC BeanFactoryIoC Service Provider 12 BeanFactory 13 BeanFactoryBeanFactory BeanFactory14 BeanFactoryBeanFactory 4-1BeanFactory 15 4-1BeanFactory 16 public interface BeanFactory {String FACTORY_BEAN_PREFIX = "&";Object getBean(String name) throws BeansException; 17 27. 22 Spring IoC Object getBean(String name, Class requiredType) throws BeansException; /*** @since 2.5*/ Object getBean(String name, Object[] args) throws BeansException; boolean containsBean(String name); boolean isSingleton(String name) throws NoSuchBeanDefinitionException; /*** @since 2.0.3*/ boolean isPrototype(String name) throws NoSuchBeanDefinitionException; /*** @since 2.0.1*/ boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException; Class getType(String name) throws NoSuchBeanDefinitionException; String[] getAliases(String name); } getBean containsBeanbean API4.1 BeanFactory BeanFactory BeanFactory BeanFactory FX Pull BeanFactoryIoCBeanFactoryPush BeanFactoryIoC BeanFactoryIoC 4-2FX4-2FX 1-FXNewsProvider public class FXNewsProvider {... }2-IFXNewsListener public interface IFXNewsListener {... } public class DowJonesNewsListener implements IFXNewsListener 28. 4.1 TBeanFactoryT 23{ ... }3-IFXNewsPersister public interface IFXNewsPersister 2 {... } 3 public class DowJonesNewsPersister implements IFXNewsPersister {...4 }BeanFactoryIoC 5 BeanFactory XML6 4-34-3 BeanFactoryXML 7 8 9 ...10 BeanFactorymain 11 FXNewsProvider newsProvider = new FXNewsProvider(); newsProvider.getAndPersistNews(); 12 BeanFactory BeanFactory BeanFactoryFXNewsProvider 13 BeanFactory container = new XmlBeanFactory(new ClassPathResource("")); FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("djNewsProvider"); newsProvider.getAndPersistNews(); 14 ApplicationContext container = 15 new ClassPathXmlApplicationContext(""); FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("djNewsProvider"); newsProvider.getAndPersistNews(); 16 ApplicationContext container = 17 29. 24 Spring IoC new FileSystemXmlApplicationContext(""); FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("djNewsProvider"); newsProvider.getAndPersistNews();BeanFactoryBeanFactory 4.2 BeanFactory BeanFactoryIoC Service Provider IoC Service Provider BeanFactory 4.2.1 BeanFactory FX4-44-4BeanFactoryFX public static void main(String[] args) {DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();BeanFactory container = (BeanFactory)bindViaCode(beanRegistry);FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("djNewsProvider");newsProvider.getAndPersistNews(); }public static BeanFactory bindViaCode(BeanDefinitionRegistry registry) { AbstractBeanDefinition newsProvider = new RootBeanDefinition(FXNewsProvider.class,true); AbstractBeanDefinition newsListener = new RootBeanDefinition(DowJonesNewsListener.class,true); AbstractBeanDefinition newsPersister = new RootBeanDefinition(DowJonesNewsPersister.class,true); // bean registry.registerBeanDefinition("djNewsProvider", newsProvider); registry.registerBeanDefinition("djListener", newsListener); registry.registerBeanDefinition("djPersister", newsPersister); // // 1. ConstructorArgumentValues argValues = new ConstructorArgumentValues(); argValues.addIndexedArgumentValue(0, newsListener); argValues.addIndexedArgumentValue(1, newsPersister); newsProvider.setConstructorArgumentValues(argValues); // 2. setter SpringBeanFactoryConfiguration MetadataConfiguration Metadata 30. 4.2 TBeanFactoryT F F 25 MutablePropertyValues propertyValues = new MutablePropertyValues();propertyValues.addPropertyValue(new ropertyValue("newsListener",newsListener));propertyValues.addPropertyValue(new PropertyValue("newPersistener",newsPersister));newsProvider.setPropertyValues(propertyValues);// return (BeanFactory)registry;2} BeanFactory BeanDefault- 3 ListableBeanFactory BeanFactory DefaultListableBean- FactoryBeanFactoryBeanDefinitionRegistry BeanFactoryBeanBeanFactory4 Bean BeanFactory Bean BeanDefinitionRegistryBeanBeanFactory5 Bean4-36 7 8 9 4-3 BeanFactoryBeanDefinitionRegistryDefaultListableBeanFactory10 BeanDefinitionRegistry BeanFactoryBookFactory BookDefinitionRegistry11 BeanDefinitioninstance BeanDefinitionclass12 BeanFactoryBeanFactory RootBeanDefinition ChildBean-13 DefinitionBeanDefinition main DefaultListableBeanFactory BeanDefinition-14 RegistrybindViaCode bindViaCodeBeanFactory15 FXNewsProvider bindViaCodeBeanDefinition RootBeanDefinition BeanDefinition 16 BeanDefinitionBeanDefinitionRegistry FXNewsProvider ConstructorArgument-17 31. 26 Spring IoC ValuessetterSpring settersetter4 BeanFactoryBeanDefini- tionRegistry DefaultListableBeanFactoryBeanFactoryBeanDefinitionRegistryBeanDefinitionRegistryBeanFactory4.2.2 SpringIoCPropertiesXML SpringIoC BeanDefinitionReaderBeanDefinitionReader BeanDefinitionBeanDefinition BeanDefinitionRegistryBeanDefinitionRegistryBean BeanDefinitionBeanDefinition- ReaderBeanDefinitionRegistry BeanDefinitionRegistry beanRegistry = ; BeanDefinitionReader beanDefinitionReader = new BeanDefinitionReaderImpl(beanRegistry); beanDefinitionReader.loadBeanDefinitions(""); // BeanDefinitionRegistry1. Properties Spring org.springframework.beans.factory.support.PropertiesBeanDefinition- ReaderPropertiesBeanDefinitionReader FXNews4-54-5Properties djNewsProvider.(class)=..FXNewsProvider # ----------------------- djNewsProvider.$0(ref)=djListener djNewsProvider.$1(ref)=djPersister # ----------setter--------- # djNewsProvider.newsListener(ref)=djListener # djNewsProvider.newPersistener(ref)=djPersisterdjListener.(class)=..impl.DowJonesNewsListenerdjPersister.(class)=..impl.DowJonesNewsPersister Spring PropertiesBeanDefinitionReader 32. 4.2 TBeanFactoryT F F 27SpringAPI4-5 djNewsProviderbeanName.(class)djNewsProvider.class=...Spring 1.2.6.(class)djListenerdjPersister 2 beanName.$[number]beanName3djListenerdjPersister$0$1(ref) (ref) (ref) PropertiesBeanDefinitionReader djListener djPersisterString 4 FXNewsProvider setterProperties5Propertiessetter6 newsListener newPersistenerFXNewsProvidersetter7setterProperties8(ref)BeanFactory 4-6 9 4-6 PropertiesBeanFactory10public static void main(String[] args){ DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();11 BeanFactory container = (BeanFactory)bindViaPropertiesFile(beanRegistry); FXNewsProvider newsProvider =(FXNewsProvider)container.getBean("djNewsProvider");12 newsProvider.getAndPersistNews();} public static BeanFactory bindViaPropertiesFile(BeanDefinitionRegistry registry)13{ PropertiesBeanDefinitionReader reader =new PropertiesBeanDefinitionReader(registry); 14 reader.loadBeanDefinitions("classpath:../../binding-config.properties"); return (BeanFactory)registry;} 15 PropertiesProperties BeanDefinitionReader16 PropertiesBeanDefinitionReader 17 33. 28 Spring IoC SpringPropertiesBeanDefinitionReaderSpring PropertiesPropertiesBeanDefinitionReader PropertiesBean-DefinitionReader 2. XML XMLSpringXML SpringXMLProperties XML Spring 2.xXMLDTDDocument Type Definition2.xXSDXML Schema Definition DTDDTDXSD DTD FXXML4-74-7FXXML "http://www.springframework.org/dtd/spring-beans.dtd"> Properties XMLBeanFactory 4-84-8XMLBeanFactorypublic static void main(String[] args){ Spring 34. 4.2 TBeanFactoryT F F29 DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();BeanFactory container = (BeanFactory)bindViaXMLFile(beanRegistry);FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("djNewsProvider");newsProvider.getAndPersistNews();}2public static BeanFactory bindViaXMLFile(BeanDefinitionRegistry registry){3 XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); reader.loadBeanDefinitions("classpath:../news-config.xml"); return (BeanFactory)registry; // 4 //return new XmlBeanFactory(new ClassPathResource("../news-config.xml"));}PropertiesPropertiesBeanDefinitionReaderSpringXML5 BeanDefinitionReader XmlBeanDefinitionReader XmlBeanDefinitionReaderSpringXML 6 BeanDefinitionBeanDefinitionRegistryDefault- ListableBeanFactoryBeanFactory XmlBeanDefinitionReader XML Spring Default- 7 ListableBeanFactoryXMLXmlBeanFactory XmlBeanFactoryXMLBeanFactory8 PropertiesXML 9XmlBeanFactoryXmlBeanFactoryXmlBeanDefinitionReaderXML 10XmlBeanDefinitionReaderBeanDefinitionReaderXMLSpring 11 4.2.3 12 BeanFactory BeanFactoryIoC Service Provider 13 Spring 2.5Spring Spring 2.5classpath-scanning XML14 Java 5Spring 2.5Java 5 15 FXNewsProvider@Autowired @Component4-9FXNews 16 4-9 FXNews@Componentpublic class FXNewsProvider17 35. 30Spring IoC {@Autowiredprivate IFXNewsListener newsListener;@Autowiredprivate IFXNewsPersister newPersistener; public FXNewsProvider(IFXNewsListener newsListner,IFXNewsPersister newsPersister){this.newsListener = newsListner;this.newPersistener = newsPersister;}...} @Componentpublic class DowJonesNewsListener implements IFXNewsListener{ ...} @Componentpublic class DowJonesNewsPersister implements IFXNewsPersister{ ...} @AutowiredSpring @ComponentSpring 2.5classpath-scanningSpring @Autowired@Component 4-104-10 classpath-scanningpackage@Component @Autowired public static void main(String[] args){ ApplicationContext ctx = new ClassPathXmlApplicationContext(""); FXNewsProvider newsProvider = (FXNewsProvider)container.getBean("FXNewsProvider"); 36. 4.3 TBeanFactoryT XML 31newsProvider.getAndPersistNews(); }Spring 2.5 2 Google Guice Google Guice 34.3 BeanFactoryXML4XMLSpringSpring SpringXMLSpring5 IoCSpringXML6 4.3.1 XML Spring IoC BeanFactory 7 ApplicationContextXMLXMLSpring 2.0 SpringDTDSpringXML DOCTYPE8 "http://www.springframework.org/dtd/spring-beans.dtd"> 9 ... 10 Spring 2.0SpringDTDDOCTYPE XML SchemaSpring 2.0 11 4-11XSD4-11XSDSpring 12 SpringBeanXML XML 1. XML01 4-44-4 attribute default-lazy-inittruefalsefalse default-autowirenobyNamebyTypeconstructorautodetect nobean default-dependency-checknoneobjectssimpleallnone default-init-method default-destroy-method default-init-method bean 38. 4.3 TBeanFactoryT XML 33 2. 2 3 4 5 A.xml B.xml A.xml B.xmlA.xml 6 7 8 dataSourceForMasterDatabase 9 dataSourceForMasterDatabasemasterDataSource 10 4.3.2 BeanSpringXML11 12 13 id14idbeanNameidbeanNamedjNewsListener 15idid beanName id name 16 alias idnamenameid/ namenameid class class 4.3.3 Help Me, Help You SpringIoCXML IoC setterXML 1. XML SpringIoC djNewsProviderBean Spring XML typeindex Warcraft 40. 4.3 TBeanFactoryT XML 35 type 4-12 2 4-12 public class MockBusinessObject { 3private String dependency1;private intdependency2;public MockBusinessObject(String dependency) 4 { this.dependency1 = dependency; } 5 public MockBusinessObject(int dependency) { this.dependency2 = dependency;6 } ...@Override 7 public String toString() { return new ToStringBuilder(this) .append("dependency1", dependency1) 8 .append("dependency2", dependency2).toString(); } } 9 10111111 11 BeanFactorytoString()Spring 12 ..MockBusinessObject@f73c1[dependency1=111111,dependency2=0] inttype13 14111111 15 ..MockBusinessObject@f73c1[dependency1=,dependency2=111111] 16 index Spring 17 41. 36 Spring IoC Spring4-134-13 public class MockBusinessObject {private String dependency1;private String dependency2;public MockBusinessObject(String dependency1,String dependency2) { this.dependency1 = dependency1; this.dependency2 = dependency2; } ...@Override public String toString() { return new ToStringBuilder(this) .append("dependency1", dependency1) .append("dependency2", dependency2).toString(); } } ..MockBusinessObject@1ef8cf3[dependency1=11111,dependency2=22222]1111122222 index ..MockBusinessObject@ecd7e[dependency1=22222,dependency2=11111] index0index 0index12. setterXML Springsetter 42. 4.3 TBeanFactoryT XML 37nameattribute valueref 2 3 4 5 6 setter 7 8 MockBusinessObject String 9 dependency2setter4-144-14 setter10public class MockBusinessObject { private String dependency1; private String dependency2;11public MockBusinessObject(String dependency){ 12this.dependency1 = dependency;} public void setDependency2(String dependency2) {13this.dependency2 = dependency2;}... 14} 3. 15 Springbeanrefidrefvaluenulllistsetmap16 props 17 43. 38 Spring IoC (1) valueString JavawrapperintInteger 111111222222 value (2) refreflocalparentbean beanName4-15ref4-15localparentbean constructor-arg> localparentbean localXMLid parent BeanFactoryHierarchicalBeanFactoryA B BAAB BeanFactory parentContainer = new XmlBeanFactory(new ClassPathResource(" ")); BeanFactory childContainer = new XmlBeanFactory(new ClassPathResource(" "),parentContainer); childContainerparentparentContainer 44. 4.3 TBeanFactoryT XML 39 beanbean (3) 2 3djNewsListeneridrefidref4 beanNamebeanName idref5 6 local beanbean (4) 7 FXDowJonesNews- 8 ListenerFXNewsProvider 4-16 9 4-16 10 11 12 djNewsProvider 13 idid 14 15 16 (5) java.util.List 17 45. 40 Spring IoC collection4-17 4-17 public class MockDemoObject {private List param1;private String[] param2;...// settergetter... } somethingstringValue1stringValue2 param1 (6) setJava Collectionjava.util. Set4-184-18 public class MockDemoObject {private Set valueSet;// settergetter... } something ... 46. 4.3 TBeanFactoryT XML 41 ClassCastException (7) listmapkey2 Collection3 java.util.Map4-19 4 4-19 public class MockDemoObject {5private Map mapping;// settergetter}... 6 7something 8 objectKey9 ... 10...11 java.util.Map12 entrykeykey-ref 13 Collection entry14 entry 15 valuevalue-ref keykey-ref164-20 17 47. 42 Spring IoC 4-20 public class MockDemoObject {private Map mapping;// settergetter... } ... ...(8) map java.util.PropertiesPropertiesStringkey 4-214-21 public class MockDemoObject {private Properties emailAddrs;// settergetter... } [email protected]@spring21.cn... key java.util. Properties (9) Stringvalue ""nullstring nullString 4-22 48. 4.3 TBeanFactoryT XML 434-22 public class MockDemoObject {private String param1;private Object param2;2// settergetter... } 3 4 5 public class MockDemoObject {private String param1=null; 6private Object param2=null;// settergetter... }7 4. depends-on8 bean beanbean beanA9 BAB 10 public class SystemConfigurationSetup {static11{DOMConfigurator.configure("");// } 12... }log4j13 SystemConfigurationSetupClassAlog4jbean depends-onSystemConfigurationSetup 14 15 log4jstatic block 16 depends-on 17 49. 44Spring IoC ClassAClassAdepends-on beanName5. autowire beanSpirngbean beanautowirebean bean Spring5nobyNamebyTypeconstructorautodetect no bean byName XMLbeanbeanName beanbean public class Foo{ private Bar emphasisAttribute; ... // setter}public class Bar{ ...} fooBeanautowire byNamebeanidemphasisAttributeFoo byType beanautowirebyTypebean beanbean 50. 4.3 TBeanFactoryT XML 45beanbean byNameFoobeanBarbean beanFoobean 2 byType bean 3 byTypeautowirebyNameautowirebyType 4 5 constructor 6 byNamebyTypepropertyconstructor byTypeconstructor byType 7 beanbyType bean 4-23construtor8 4-23 construtor9public class Foo{ private Bar bar;10 public Foo(Bar arg) { this.bar = arg; } 11 ...}1213 autodetect byTypeconstructor14 byTypeconstructor byType 15 16 String Classes StringClasses 17 51. 46 Spring IoC (1) (2) (1) (2) byTypebean byName bean (3) Spring IDEXML default-autowire autowiredefault-autowireno byType ... 6. dependency-check dependency-check checkrecheck setter dependency-check 4 nonedependency-checknone simpledependency-checksimple collection object 52. 4.3 TBeanFactoryT XML 47 allsimpleobjectcollection 7. lazy-init 2 lazy-initApplicationContextbean BeanFactoryApplicationContext3 singletonbean bean bean 4 ApplicationContextlazy-init 5ApplicationContext not-lazy-init-bean6 lazy-init-bean lazy-init-beanlazy-inittruebean7 beanlazy-init-bean lazy-init-bean 8 910lazy-init-bean not-lazy-init-bean lazy-init-bean11 lazy-init-beanbeanbean bean12 4-24 13 4-24 14 15 ...16 singleton4.3.517 53. 48Spring IoC 4.3.4 beanbeanbean FXNewsProvider class SpecificFXNewsProvider extends FXNewsProvider{ private IFXNewsListener newsListener; private IFXNewsPersister newPersistener; ...} FXNewsProviderIFXNewsPersisterDowJonesNews- Persister4-254-25 IFXNewsPersisterFXNewsProviderSpecificFXNews-Provider XML bean4-26 4-26 FXNewsProviderSpecificFXNewsProvider 54. 4.3 TBeanFactoryT XML 49 subNewsProviderparentsuperNewsProvider superNewsProvider2 parentabstractbean 3 4-27 4-27 FXNewsProviderSpecificFXNewsProvider 4 5 7 8 9newsProviderTemplatebeanabstracttruebean class class 10 abstract="true"bean superNews- ProvidersubNewsProviderparent11 bean abstract 12 abstracttruebean abstracttrueApplicationContext ApplicationContextbean13 abstractbean4.3.5 bean scope14 BeanFactoryIoC Service Provider 15 scopebeanscope scope 16 scope scopescope 17 55. 50 Spring IoC scope Springbeanscopesingletonprototype2.0 scoperequestsessionglobal sessionWeb WebApplicationContextscope singletonscopescopescope XSDDTD:XSD:scope 1. singleton bean beanscope singleton scopeSpringIoC IoC 4-5Springsingletonbean 4-5 singleton scopeGoF Singleton singletonbeanbean SingletonClassloadersingletonbean singletonbean Gang of FourDesign Patterns: Elements of Reusable Object Software 56. 4.3 TBeanFactoryT XML 51bean singletonbean singletonbean bean2 beanscopesingletonscope 3 4 52. prototypeprototype scopebean 6 7 prototype beanscopeprototype8 beanscopesingleton9 10beanscopeprototype prototypescopebean11Spring 4-6prototype scopebean 12 13 14 15 16 17 57. 52 Spring IoC 4-6 prototype scopebeanscopeprototype 3. requestsessionglobal session scopeSpirng 2.0singletonprototype WebXmlWebApplicationContext6 scope scope beanscopeXSDXML requestrequestSpring XmlWebApplicationContext HTTP Request- Processor 10HTTP 1010RequestProcessor requestprototype session Websessionsession scopesession Springsession UserPreferences 58. 4.3 TBeanFactoryT XML 53requestsession scopebeanrequest scopebean global sessionuserPreferencesscope 2 global sessionportletWebportletglobal3 sessionservletWebscopesession scope 44. scopeSpring 2.0scope scopesingletonprototype 5 requestsessionglobal sessionscopescope org.springframework.beans.factory.config.Scope 6 public interface Scope {Object get(String name, ObjectFactory objectFactory); 7 Object remove(String name);void registerDestructionCallback(String name, Runnable callback); 8 String getConversationId(); } 9scopeScope4 getremove http://www.jroller.com/eu/entry/implementing 10 _efficinet_id_generatorThreadScope4-284-28ThreadScope11 public class ThreadScope implements Scope {private final ThreadLocal threadScope = new ThreadLocal() { protected Object initialValue() { 12 return new HashMap(); } };13 public Object get(String name, ObjectFactory objectFactory) { Map scope = (Map) threadScope.get(); Object object = scope.get(name);14 if(object==null) { object = objectFactory.getObject();} scope.put(name, object);15 return object; } 16 public Object remove(String name) { Map scope = (Map) threadScope.get();} return scope.remove(name);17 59. 54Spring IoC public void registerDestructionCallback(String name, Runnable callback) { } ... }ScopeMore fun with Spring scopeshttp://jroller. com/eu/entry/more_fun_with_spring_scopesPageScope ScopeScopebean ConfigurableBeanFactoryscope void registerScope(String scopeName, Scope scope); scopeNamebeanSpringscope requestsessionscopeScope ThreadScope BeanFactory Configurable- BeanFactoryScope Scope threadScope = new ThreadScope(); beanFactory.registerScope("thread",threadScope); beanthreadbeanscope ThreadScope ConfigurableBeanFactoryregisterScopescopeSpring scope BeanFactoryPostProcessor BeanFactoryPost- Processororg.springframework.beans.factory.config.Custom- ScopeConfigurerApplicationContextBeanFactoryPost- ProcessorCustomScopeConfigurerThread- Scope4-294-29CustomScopeConfigurerscope beanscope threadthreadscope Spring AOP scopebean requestsessionglobal session4.3.6 FactoryBean 60. 4.3 TBeanFactoryT XML 55 4-30Foo BarInterface 2 4-30BarInterfaceFoo public class Foo3 {private BarInterface barInstance;public Foo() 4{// // instance = new BarInterfaceImpl();}5// ... }6 7 Factory Method 8 4-314-31Foo 9 public class Foo {private BarInterface barInterface;public Foo() 10{// barInterface = BarInterfaceFactory.getInstance();// 11// barInterface = new BarInterfaceFactory().getInstance();}... } 12 SpringIoC Foo13 14 1. Static Factory Method BarInterface 15 BarInterface StaticBarInterface- Factory 16 public class StaticBarInterfaceFactory {public static BarInterface getInstance(){17 61. 56 Spring IoC return new BarInterfaceImpl(); } }Foosetter FooBarInterface classfactory-method getInstanceBarInterfaceImpl foobarBarInterfaceImpl StaticBarInterfaceFactory getInstance() StaticBarInterfaceFactoryBarInterface public class StaticBarInterfaceFactory {public static BarInterface getInstance(Foobar foobar){return new BarInterfaceImpl(foobar);} }4-32 4-32 bean 62. 4.3 TBeanFactoryT XML 572. Instance Factory Method bean BarInterface 2 public class NonStaticBarInterfaceFactory {public BarInterface getInstance() 3{return new BarInterfaceImpl();}...4 }NonStaticBarInterfaceFactory5 67 8 NonStaticBarInterfaceFactorybean bar factory-bean 9classfactory-method 103. FactoryBean11 FactoryBeanSpring BeanFactoryFactoryBeanBeanFactory12BeanBean Factory13XMLJava Spring org.spring- framework.beans.factory.FactoryBean Fac- 14toryBeanFactoryBeanSpring 15 FactoryBean org.springframework.beans.factory.FactoryBean16 public interface FactoryBean { 17 63. 58Spring IoC Object getObject() throws Exception;Class getObjectType();boolean isSingleton();}getObject()FactoryBean getObjectType()getObject() nullisSingleton()getObject() singletonsingletontruefalse4-33FactoryBean4-33 NextDayDateFactoryBeanimport org.joda.time.DateTime;import org.springframework.beans.factory.FactoryBean; public class NextDayDateFactoryBean implements FactoryBean { public Object getObject() throws Exception {return new DateTime().plusDays(1);} public Class getObjectType() {return DateTime.class;} public boolean isSingleton() {return false;} } NextDayDateFactoryBeanbeanNextDayDateDisplayer FactoryBeanNextDayDateDisplayerpublic class NextDayDateDisplayer{ private DateTime dateOfNextDay; // setter // ...} NextDayDateDisplayer dateOfNextDay DateTime NextDayDateFactoryBeanFactoryBeanbeanid 64. 4.3 TBeanFactoryT XML 59FactoryBeanFactoryBean FactoryBeanbeanid& 4-34FactoryBeanFactoryBean 2 4-34 &FactoryBean Object nextDayDate = container.getBean("nextDayDate"); assertTrue(nextDayDate instanceof DateTime);3 Object factoryBean = container.getBean("&nextDayDate"); assertTrue(factoryBean instanceof FactoryBean); assertTrue(factoryBean instanceof NextDayDateFactoryBean);4 Object factoryValue = ((FactoryBean)factoryBean).getObject(); assertTrue(factoryValue instanceof DateTime); 5 assertNotSame(nextDayDate, factoryValue); assertEquals(((DateTime)nextDayDate).getDayOfYear(),((DateTime)factoryValue).getDayOfYear());SpringFactoryBeanFactoryBean 6 FactoryBeanJavadoc JndiObjectFactoryBean7 LocalSessionFactoryBean SqlMapClientFactoryBean8 ProxyFactoryBean TransactionProxyFactoryBean 9 4.3.7 beanscopeprototype10 SpringMethod Injection Method Replacement prototypescopebean 11 FX NewsFXNewsBean scopeprototype12 MockNewsPersister IFXNewsPersister FXNewsBean4-35 13 4-35 MockNewsPersister public class MockNewsPersister implements IFXNewsPersister {private FXNewsBean newsBean; 14public void persistNews(FXNewsBean bean) {persistNewes();15}public void persistNews(){System.out.println("persist bean:"+getNewsBean()); 16}public FXNewsBean getNewsBean() { }return newsBean; 17 65. 60 Spring IoC public void setNewsBean(FXNewsBean newsBean) { this.newsBean = newsBean; } } MockNewsPersisterpersistNews BeanFactory container = new XmlBeanFactory(new ClassPathResource("..")); MockNewsPersister persister = (MockNewsPersister)container.getBean("mockPersister"); persister.persistNews(); persister.persistNews(); persist bean:..domain.FXNewsBean@1662dc8 persist bean:..domain.FXNewsBean@1662dc8 persistNews getNewsBean()FXNewsBeanFXNewsBeanprototype FXNewsBeanscopeprototype FXNewsBean prototype scope FXNewsBean MockNewsPersisterMockNewsPersisterFXNewsBean getNewsBean() FXNewsBean MockNewsPersister MockNewsPersister FXNewsBean getNewsBean() FXNewsBean 1. SpringMethod Injection getNewsBean [abstract] theMethodName(no-arguments); CglibgetNewsBean() 66. 4.3 TBeanFactoryT XML 61namebean getNewsBeanFXNewsBean persist bean:..domain.FXNewsBean@18aaa1e 2persist bean:..domain.FXNewsBean@a6aeed 3 FXNewsBean prototype4 FXNewsBeanprototype 5 6 2. 7 BeanFactoryAware getNewsBean() Bean-8 FactorygetBean("newsBean")FXNewsBean MockNewsPersisterBeanFactory9 SpringBeanFactoryAwarebean beanbeanBeanFactoryBeanFactory- Aware 10public interface BeanFactoryAware { void setBeanFactory(BeanFactory beanFactory) throws BeansException; 11} MockNewsPersister BeanFactory MockNews- Persister4-36 12 4-36 BeanFactoryAwareMockNewsPersister 13public class MockNewsPersister implements IFXNewsPersister,BeanFactoryAware { private BeanFactory beanFactory; public void setBeanFactory(BeanFactory bf) throws BeansException { 14this.beanFactory = bf;}public void persistNews(FXNewsBean bean) {persistNews(); 15}public void persistNews(){16System.out.println("persist bean:"+getNewsBean());}public FXNewsBean getNewsBean() {return beanFactory.getBean("newsBean"); 17 67. 62Spring IoC }} persist bean:..domain.FXNewsBean@121cc40persist bean:..domain.FXNewsBean@1e893df ObjectFactoryCreatingFactoryBeanObjectFactoryCreatingFactoryBean Spring FactoryBean ObjectFactory ObjectFactoryCreatingFactoryBeanObjectFactory ObjectFactoryCreatingFactoryBean BeanFactoryAware ObjectFactorySpring BeanFactory ObjectFactoryFXNewsBean4-37 MockNewsPersister4-37 ObjectFactoryMockNewsPersisterpublic class MockNewsPersister implements IFXNewsPersister { private ObjectFactory newsBeanFactory; public void persistNews(FXNewsBean bean) {persistNews();}public void persistNews(){System.out.println("persist bean:"+getNewsBean());}public FXNewsBean getNewsBean() {return newsBeanFactory.getObject();}public void setNewsBeanFactory(ObjectFactory newsBeanFactory) {this.newsBeanFactory = newsBeanFactory;}} MockNewsPersisterObjectFactory ObjectFactoryCreatingFactoryBean4-384-38 ObjectFactoryCreatingFactoryBean 68. 4.3 TBeanFactoryT XML 632persist bean:..domain.FXNewsBean@ecd7epersist bean:..domain.FXNewsBean@1d520c43 ServiceLocatorFactoryBean ObjectFactoryCreatingFactory-Bean FactoryBean SpringObjectFactoryJavadocJavadoc45 3. 6 AOP 7 FXNewsProvidergetAndPersistNews 8 Method Replacement9 org.springframework.beans.factory.support.MethodReplacer 10 4-39MethodReplacer11 4-39FXNewsProviderMethodReplacerpublic class FXNewsProviderMethodReplacer implements MethodReplacer { private static final transient Log logger = 12LogFactory.getLog(FXNewsProviderMethodReplacer.class); public Object reimplement(Object target, Method method, Object[] args) 13throws Throwable {logger.info("before executing method["+method.getName()+"] on Object["+target.getClass().getName()+"]."); 14System.out.println("sorry,We will do nothing this time."); logger.info("end of executing method["+method.getName()+ 15"] on Object["+target.getClass().getName()+"].");return null;}} 16 FXNewsProv- iderbean4-40 17 69. 64 Spring IoC 4-40FXNewsProvider ...FXNewsProvidergetAndPersistNews 771 [main] INFO ..FXNewsProviderMethodReplacer- before executing method[getAndPersistNews]on Object[..FXNewsProvider$$EnhancerByCGLIB$$3fa709d3]. sorry,We will do nothing this time. 771 [main] INFO ..FXNewsProviderMethodReplacer- end of executing method[getAndPersistNews]on Object[..FXNewsProvider$$EnhancerByCGLIB$$3fa709d3]. FXNewsProvidergetAndPersistNews Spring AOP 4.4 SpringIoCSpringIoC SpringIoC 4-7SpringMagic Happens Here 70. 4.4 65 2344-7 5 4.4.1 6 SpringIoC4-7Configuration MetadataXML 7 SpringIoC 8 Bean4-8 SpringIoC 9 101112131415 4-81. 16 Configuration MetaData BeanDefinitionReaderConfiguration MetaData 17 71. 66 Spring IoC BeanDefinitionbean BeanDefinitionBeanDefinitionRegistry 4-9 4-9 XMLBeanDefinition 2. Bean beanBeanDefinitionBeanDefini- tionRegistrygetBean getBean BeanDefinition 4.4.2 SpringBeanFactoryPostProcessor BeanDefinition BeanDefinition beanbean BeanFactoryPostProcessor org.springframework. beans.factory.config.BeanFactoryPostProcessor Bean- FactoryPostProcessorSpringorg.springframework.core. OrderedBeanFactoryPostProcessor SpringBeanFactoryPostProcessor BeanFactoryPostProcessor org.springframework.beans. factory.config.PropertyPlaceholderConfigurer org.springframework.beans.factory. config.Property OverrideConfigurerBeanFactoryPostProcessor Spring org.springframework.beans.factory.config.CustomEditorConfigurer Pro- pertyEditorPropertyEditorBeanFactoryPostProcessorJavadoc BeanFactoryPostProcessor IoC BeanFactoryApplicationContext 72. 4.4 67 BeanFactoryBeanFactoryPostProcessor 4-414-41BeanFactoryBeanFactoryPostProcessor2// BeanFactoryConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("..."));// BeanFactoryPostProcessorPropertyPlaceholderConfigurer propertyPostProcessor = new PropertyPlaceholderConfigurer();3propertyPostProcessor.setLocation(new ClassPathResource("..."));// propertyPostProcessor.postProcessBeanFactory(beanFactory);4 BeanFactoryPostProcessor BeanFactoryPostProcessor5 ApplicationContextApplicationContext BeanFactoryPostProcessorBeanFactory ApplicationContext BeanFactoryPostProcessor XML BeanFactoryPost-6 Processor4-42BeanFactoryPostProcessor ApplicationContext 7 4-42ApplicationContextBeanFactoryPostProcessor... 89conf/jdbc.propertiesconf/mail.properties 10 ...11SpringBeanFactoryPostProcessor1. PropertyPlaceholderConfigurer12 XML XML13 properties propertiesPropertyPlaceholderConfigurerXMLPlaceHolder 14 properties PropertyPlaceholderConfigurer4-42XML15 4-43 XML16 4-43 17 73. 68Spring IoC ${jdbc.url}${jdbc.driver}${jdbc.username}${jdbc.password}truetruetrue180000360000SELECT 1100 AntVelocity${property} jdbc.propertiesjdbc.url=jdbc:mysql://server/MAIN?useUnicode=true&characterEncoding=ms932& failOverReadOnly=false&roundRobinLoadBalance=truejdbc.driver=com.mysql.jdbc.Driverjdbc.username=your usernamejdbc.password=your passwordBeanFactoryBeanFac- tory${jdbc.url}${jdbc.driver} PropertyPlaceholderConfigurer BeanFactoryPostProcessorproperties BeanDefinition beanbean PropertyPlaceholderConfigurerproperties Java SystemProperties setSystemPropertiesMode() setSystemProper- tiesModeName() System Properties PropertyPlaceholder- ConfigurerSYSTEM_PROPERTIES_MODE_FALLBACKSYSTEM_PROPERTIES_MODE_NEVERSYSTEM_ PROPERTIES_MODE_OVERRIDESYSTEM_PROPERTIES_ MODE_FALLBACK 74. 4.4 69properties SystemProperties System PropertiesPropertyPlaceholderConfigurerJavadoc 2. PropertyOverrideConfigurer PropertyPlaceholderConfigurer bean property 2 propertiesPropertyPlaceholderConfigurer PropertyOverrideConfigurer3 PropertyOverrideConfigurerbeanproperty dataSource 4 maxActive100100PropertyOverrideConfigurer properties1002005 dataSource.maxActive=200dataSourcemaxActive2006 XML100PropertyOverrideConfigurerproperties XMLbeanpropertyXML bean7 property PropertyOverrideConfigurerproperties bean beanproperty 8 PropertyOverrideConfigurer beanName.propertyName=value 9propertiesXMLbeanbeanName idpropertymaxActive 10dataSourcePropertyOverrideConfigurerpropeties # pool-adjustment.properties11 dataSource.minEvictableIdleTimeMillis=1000 dataSource.maxActive=50PropertyOverrideConfigurerdataSource 12 pool-adjustment.properties 13 pool-adjustment.propertiesXML 14 PropertyOverrideConfigurerbean property properties PropertyOverrideConfigurer 15 PropertyResourceConfigurerprotectedconvertPropertyValue bean16 PropertyPlaceholderConfigurerPropertyResourceConfigurer PropertyPlaceholderConfigurer17 75. 70 Spring IoC 3. CustomEditorConfigurer BeanFactoryPostProcessorBeanDefinition CustomEditorConfigurerBeanFactoryPostProcessor BeanDefinition XMLpropertiesXMLString XML CustomEditorConfigurer SpringJavaBeanPropertyEditorString PropertyEditor PropertyEditorSpringJavaBean PropertyEditorjava.lang.String.java.awt. Colorjava.awt.FontSpringProperty- Editor PropertyEditor org.springframework. beans.propertyeditors SpringPropertyEditor StringArrayPropertyEditor PropertyEditor CSV String[] ByteArrayPropertyEditorCharArrayPropertyEditorProperty- EditorJavadoc ClassEditorStringclassClass Class.forName(String)String[] ClassArrayEditor FileEditorSpringjava.io.FilePropertyEditor PropertyEditorInputStreamEditorURLEditor LocaleEditor java.util.Locale PropertyEditor Local- eEditorLocaleJavadoc PatternEditor Java SE 1.4 java.util.regex.Pattern Property- Editorjava.util.regex.PatternJavadoc PropertyEditor PropertyEditor PropertyEditor CustomEditorConfigurerPropertyEditor PropertyEditor DateLocale yyyy-MM-ddyyyyMMdd SpringCustomDateEditor PropertyEditor PropertyEditor PropertyEditor 76. 4.4 71yyyy/MM/ddPropertyEditor java.beans.PropertyEditor java.beans.Property- EditorSupportjava.beans.PropertyEditor DatePropertyEditor String java.util.Date 2 setAsText(String)PropertyEditor4-44 3 4-44 DatePropertyEditorpublic class DatePropertyEditor extends PropertyEditorSupport {4 private String datePattern; @Overridepublic void setAsText(String text) throws IllegalArgumentException { 5DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(getDatePattern());Date dateValue = dateTimeFormatter.parseDateTime(text).toDate();setValue(dateValue); 6}public String getDatePattern() {return datePattern;7}public void setDatePattern(String datePattern) {this.datePattern = datePattern;}8}StringsetAsText(String)9 getAsText() CustomEditorConfigurerPropertyEditor 10 DateFoojava.util.Date 4-45 11 4-45 DateFoopublic class DateFoo { 12 private Date date; public Date getDate() {return date; 13}public void setDate(Date date) {this.date = date;14}} 15 2007/10/16 16SpringPropertyEditor2007/10/16 17 77. 72 Spring IoC java.util.DateCustomEditorConfigurerDatePro- pertyEditor DatePropertyEditor String java.util. Date BeanFactory XmlBeanFactory CustomEditorConfigurerXmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("..."));//CustomEditorConfigurer ceConfigurer = new CustomEditorConfigurer();Map customerEditors = new HashMap();customerEditors.put(java.util.Date.class, new DatePropertyEditor());ceConfigurer.setCustomEditors(customerEditors);//ceConfigurer.postProcessBeanFactory(beanFactory); ApplicationContext ApplicationContext Bean- FactoryPostProcessor4-464-46CustomEditorConfigurerDatePropertyEditoryyyy/MM/ddSpring 2.0 CustomEditorConfigurer customEditors PropertyEditor 2.0 propertyEditorRegistrarsProper- tyEditororg.springframework.beans. PropertyEditorRegistrar4-474-47DatePropertyEditorRegistrarpublic class DatePropertyEditorRegistrar implements PropertyEditorRegistrar { private PropertyEditor propertyEditor;public void registerCustomEditors(PropertyEditorRegistry peRegistry) { peRegistry.registerCustomEditor(java.util.Date.class, getPropertyEditor()); }public PropertyEditor getPropertyEditor() { return propertyEditor; }public void setPropertyEditor(PropertyEditor propertyEditor) { this.propertyEditor = propertyEditor; 78. 4.4 73 }}2.0PropertyEditor4-48 4-48 CustomEditorConfigurerpropertyEditorRegistrars2PropertyEditor3 4 5 67 yyyy/MM/dd8 PropertyEditorpropertyEditorRegistrars 9 4.4.3 bean BeanFactoryPostProcessorMagic 10 bean bean BeanDefinitionBeanFactorygetBean()11 BeanBeanFactorygetBean 12 BeanFactoryA B13 AB A getBean() ApplicationContextbean14 ApplicationContextSpring bean 15 getBean()ApplicationContext org.springframework.context.support. AbstractApplicationContextrefresh()16 getBean()Beanbean getBean()Bean 17 79. 74 Spring IoC prototypebean getBean()beancreateBean() 4-10 4-10 BeanSpring newbean org.springframework.beans.factory.support.AbstractBeanFactory getBean() org.springframework.beans. factory.support.AbstractAutowireCapableBeanFactory createBean() 1. BeanBeanWrapper Strategy Patternbean CGLIBbeanorg.springframework.beans.factory.support.InstantiationStrategy SimpleInstantiationStrategy CglibSubclassingInstantiation- StrategySimpleInstantiationStrategyCGLIB CglibSubclassingInstantiationStrategy bean BeanDefintion CglibSubclassingIns- tantiationStrategybean BeanWrapper BeanWrapper BeanWrapperSpringorg.springframework.beans. BeanWrapperImplbeanbean 80. 4.4 75beanBeanWrapper BeanWrapperorg.springframework.beans.PropertyAccessor BeanWrapperPropertyEditorRegistry2 TypeConverterCustomEditorConfigurerPropertyEditor PropertyEditorBeanWrapper3 Spring BeanWrapperImpl CustomEditor- ConfigurerPropertyEditorBeanWrapperImplBeanWrapper PropertyEditorRegistryBeanWrapper4 BeanWrapperbeanJavaAPIJava Reflection API 5 4-49Spring 6 4-49 BeanWrapperObject provider = Class.forName("package.name.FXNewsProvider").newInstance();Object listener = Class.forName("package.name.DowJonesNewsListener").newInstance();7Object persister = Class.forName("package.name.DowJonesNewsPersister").newInstance(); BeanWrapper newsProvider = new BeanWrapperImpl(provider); 8newsProvider.setPropertyValue("newsListener", listener);newsProvider.setPropertyValue("newPersistener", persister); assertTrue(newsProvider.getWrappedInstance() instanceof FXNewsProvider);9assertSame(provider, newsProvider.getWrappedInstance());assertSame(listener, newsProvider.getPropertyValue("newsListener"));assertSame(persister, newsProvider.getPropertyValue("newPersistener")); 10 BeanWrapperJavaAPI4-50 JavaAPI11 4-50 JavaAPIObject provider = Class.forName("package.name.FXNewsProvider").newInstance();Object listener = Class.forName("package.name.DowJonesNewsListener").newInstance();12Object persister = Class.forName("package.name.DowJonesNewsPersister").newInstance(); Class providerClazz = provider.getClass();13Field listenerField = providerClazz.getField("newsListener");listenerField.set(provider, listener);Field persisterField = providerClazz.getField("newsListener");persisterField.set(provider, persister);14assertSame(listener, listenerField.get(provider));assertSame(persister, persisterField.get(provider));15 exception 2. Aware16 Spring AwareAware17 81. 76Spring IoC Aware org.springframework.beans.factory.BeanNameAwareSpring beanbeanName org.springframework.beans.factory.BeanClassLoaderAware beanClassloader org.springframework.util.ClassUtilsClassloader org.springframework.beans.factory.BeanFactoryAware prototype bean BeanFactoryAwareBeanFactory BeanFactory AwareBeanFactoryApplicationContext Aware BeanPostProcessorAware BeanPostProcessor ApplicationContextAware org.springframework.context.ResourceLoaderAware ApplicationContext SpringResourceLoader ResourceLoaderAwareApplicationContext ApplicationContext org.springframework.context.ApplicationEventPublisherAware ApplicationContext ApplicationEventPublisher Appli- cationEventPublisherApplicationContext ApplicationEventPublisherAware org.springframework.context.MessageSourceAware ApplicationContextMessage- SourceI18nInternationalizationMessage- Source MessageSourceAware org.springframework.context.ApplicationContextAware ApplicationContext ApplicationContextAware 3. BeanPostProcessorBeanPostProcessorBeanFactoryPostProcessorBean- PostProcessor BeanFactoryPostProcessor BeanFactoryPostProcessorBeanDefinitionBean- PostProcessor public interface BeanPostProcessor 82. 4.4 77 {Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;}2postProcessBeforeInitialization()4-10 BeanPostProcessor postProcessAfterInitialization()4-10BeanPostProcessor 3 BeanPostProcessor 4 BeanPostProcessor 4-10ApplicationContextAwareBean- 5 PostProcessorApplicationContextBeanPost- ProcessorApplicationContextApplication-6 ContextAwareProcessorBeanPostProcessorpostProcessBefore- Initialization()Aware ApplicationContextAwareProcessorpost- ProcessBeforeInitialization()4-51 7 4-51 postProcessBeforeInitialization 8public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); 9 } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher 10 (this.applicationContext); } if (bean instanceof MessageSourceAware) { 11 ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); 12 } return bean;}13 BeanPostProcessor SpringAOP 14 BeanPostProcessor org.springframework.aop.framework. autoproxy.BeanNameAutoProxyCreatorSpring AOPAOPBeanPostProcessor 15 BeanPostProcessor BeanPostProcessor16 IFXNewsListener IFXNewsListener 17 83. 78 Spring IoC BeanPostProcessor IFXNewsListener (1) IFXNewsListener PasswordDecodableIFXNewsListenerPasswordDecodable IFXNewsListener4-524-52PasswordDecodableIFXNewsListener public interface PasswordDecodable {String getEncodedPassword();void setDecodedPassword(String password); }public class DowJonesNewsListener implements IFXNewsListener,PasswordDecodable {private String password;public String[] getAvailableNewsIds() { // }public FXNewsBean getNewsByPK(String newsId) { // }public void postProcessIfNecessary(String newsId) { // }public String getEncodedPassword() { return this.password; }public void setDecodedPassword(String password) { this.password = password; } } (2) BeanPostProcessorBean PasswordDecodable 4-534-53BeanPostProcessorpublic class PasswordDecodePostProcessor implements BeanPostProcessor {public Object postProcessAfterInitialization(Object object, String beanName)throws BeansException { return object; } public Object postProcessBeforeInitialization(Object object, String beanName)throws BeansException { if(object instanceof PasswordDecodable) Marker Interface 84. 4.4 79 {String encodedPassword = ((PasswordDecodable)object).getEncodedPassword();String decodedPassword = decodePassword(encodedPassword);((PasswordDecodable)object).setDecodedPassword(decodedPassword);}return object;2}private String decodePassword(String encodedPassword) {// 3return encodedPassword;}}4 (3) BeanPostProcessor BeanPostProcessor PasswordDecodePostProcessor5 BeanFactoryBeanPostProcessor ConfigurableBeanFactoryaddBeanPostProcessor() 6ConfigurableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(...));beanFactory.addBeanPostProcessor(new PasswordDecodePostProcessor());... 7// getBean(); ApplicationContextBeanPostProcessor8 XMLApplicationContext BeanPostProcessorPasswordDecodePostProcessor 9 10 ...11BeanPostProcessorSpring BeanPostProcessor 12BeanPostProcessororg.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor13Springbean4-10bean InstantiationAwareBeanPost- 14ProcessorBeanPostProcessorInstantiationAwareBean-PostProcessor 15SpringBeanPostProcessor16BeanPostProcessor17 85. 80Spring IoC 4. InitializingBeaninit-method org.springframework.beans.factory.InitializingBean public interface InitializingBean { void afterPropertiesSet() throws Exception;} BeanPostProcessor InitializingBeanafterProper- tiesSet() afterPropertiesSet() Spring SpringSpring XMLinit-methodinit-method InitializingBeanafterPropertiesSet() init()init-method default-init-methodinit()ObjectLab ObjectLabKitDateCalculator DateCalculator 4-544-54 DateCalculatorpublic class FXTradeDateCalculator {public static final DateTimeFormatter FRONT_DATE_FORMATTER = DateTimeFormat.forPattern("yyyyMMdd");private static final Set holidaySet = new HashSet();private static final String holidayKey = "JPY";private SqlMapClientTemplate sqlMapClientTemplate; public FXTradeDateCalculator(SqlMapClientTemplate sqlMapClientTemplate){this.sqlMapClientTemplate = sqlMapClientTemplate;} public void setupHolidays(){List holidays = getSystemHolidays();if(!ListUtils.isEmpty(holidays)){for(int i=0,size=holidays.size();i getForwardDateCalculator() { return LocalDateKitCalculatorsFactory 3 .getDefaultInstance() .getDateCalculator(holidayKey, HolidayHandlerType.FORWARD); } 4 public DateCalculator getBackwardDateCalculator() { return LocalDateKitCalculatorsFactory 5 .getDefaultInstance() .getDateCalculator(holidayKey, HolidayHandlerType.BACKWARD); } 6 public List getSystemHolidays() { return getSqlMapClientTemplate() .queryForList("CommonContext.holiday", null); 7 }} 8 getForwardDateCalculator() getBackwardDateCalculator() Date- CalculatorsetupHolidays() DateCalculator9 4-55setup- Holidays() 10 4-55 init-method11 12 ...14 ... 15 FXTradeDateCalculator InitializingBean setup- Holidays()afterPropertiesSet()init-method 16 InitializingBeaninit-method 17 87. 82 Spring IoC InitializingBeanafterPropertiesSet() 5. DisposableBeandestroy-method singleton beanorg.springframework.beans.factory.DisposableBean beandestroy-method Callbacksingleton InitializingBean init-method DisposableBean destroy-method Spring 4-56destroy-method 4-56 ${jdbc.url}${jdbc.driver}${jdbc.username}${jdbc.password}... SpringSpring BeanFactory 4-57ConfigurableBeanFactory destroySingletons()singleton4-57ConfigurableBeanFactorydestroySingletons() public class ApplicationLauncher {public static void main(String[] args) {BasicConfigurator.configure();BeanFactory container = new XmlBeanFactory(new ClassPathResource("..."));BusinessObject bean = (BusinessObject)container.getBean("..."); 88. 4.5 83bean.doSth(); ((ConfigurableListableBeanFactory)container).destroySingletons(); // } } 2 destroySingletons()DisposableBean destroy-methodbean 3 ApplicationContextAbstractApplicationContext registerShutdownHook()RuntimeaddShutdownHook() 4 beanJavasingtletonbean AbstractApplicationContextshutdownHook 5 ApplicationContext4-58 6 4-58registerShutdownHook() public class ApplicationLauncher { 7public static void main(String[] args) {BasicConfigurator.configure();BeanFactory container = new ClassPathXmlApplicationContext("...");((AbstractApplicationContext)container).registerShutdownHook(); 8BusinessObject bean = (BusinessObject)container.getBean("...");bean.doSth();// 9} }Spring 2.0scopescope10 prototypebeanprototype 11 bean4.5 12SpringIoCBeanFactoryApplicationContext SpringBeanFactory 13 BeanFactory BeanFactoryIoC Service ProviderXMLSpringIoC 14 Configuration Metadata XML BeanFactoryApplicationContext 15BeanFactory BeanFactoryApplicationContextBeanFactory SpringIoCSpringIoC ApplicationContext 16 BeanFactoryBeanFactoryApplication- Context 17 89. 84 Spring IoC Spring IoC 5ApplicationContext Spring BeanFactoryIoC ApplicationContext BeanFactory BeanFactoryPostProces- sorBeanPostProcessorbeanbean SpringBeanFactoryXmlBeanFactoryApplica- tionContext org.springframework.context.support.FileSystemXmlApplicationContext beanApplicationContext org.springframework.context.support.ClassPathXmlApplicationContextClasspathbeanApplicationContext org.springframework.web.context.support.XmlWebApplicationContext Spring WebApplicationContext org.springframework.context.ApplicationContextJavadoc 4ApplicationContextApplicationContext BeanFactoryI18n 5.1 SpringJava SEjava.net.URL URLUniform Resource Locator HTTPFTPFilesun.net.www.protocol JavaClasspath URL 90. 5.1 85 2 Spring org.springframework.core.io.Resource org.springframework.core.io.ResourceLoader 3 5.1.1 SpringResource Spring org.springframework.core.io.Resource4 BeanFactoryBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("..."));5...ClassPathResourceResourceClasspath Resource Spring 6 org.springframework.core.io 7ByteArrayResourcebyteInputStreamByteArray-8InputStream ClassPathResource JavaClassPath ClassLoader 9 FileSystemResourcejava.io.FileURLFileFileSystemResource10 UrlResourcejava.net.URLURL InputStreamResource InputStreamResource 11ByteArrayResource 12 org.springframework.core.io.Resource5-15-1 Resource13public interface Resource extends InputStreamSource { boolean exists();14boolean isOpen(); URL getURL() throws IOException; 15File getFile() throws IOException; 16 SpringTeamURL 17 91. 86Spring IoC Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); } public interface InputStreamSource { InputStream getInputStream() throws IOException;}7 Resource org.springframework.core.io.AbstractResource 5.1.2 ResourceLoaderURL ResourceLoaderorg.spr- ingframework.core.io.ResourceLoader ResourceLoaderResourceLoader ResourceLoaderpublic interface ResourceLoader { String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX; Resource getResource(String location); ClassLoader getClassLoader();}Resource getResource(String location); 1. ResourceLoader DefaultResourceLoaderResourceLoaderorg.springframework.core.io.DefaultResource- Loader (1) classpath:ClassPathResource (2) (a) URLMalformedURLException UrlResource(b) getResourceByPath(String) DefaultResourceLoader getResourceByPath(String)ClassPathResource DefaultResourceLoader 5-2DefaultResourceLoader5-2 DefaultResourceLoaderResourceLoader resourceLoader = new DefaultResourceLoader(); 92. 5.1 87 Resource fakeFileResource = resourceLoader.getResource("D:/spring21site/README");assertTrue(fakeFileResource instanceof ClassPathResource);assertFalse(fakeFileResource.exists()); Resource urlResource1 = resourceLoader.getResource("file:D:/spring21site/README");assertTrue(urlResource1 instanceof UrlResource); 2Resource urlResource2 = resourceLoader.getResource("http://www.spring21.cn");assertTrue(urlResource2 instanceof UrlResource); 3try{ fakeFileResource.getFile(); 4 fail("no such file with path["+fakeFileResource.getFilename()+"] exists in classpath");}catch(FileNotFoundException e){ // 5}try{ urlResource1.getFile(); 6}catch(FileNotFoundException e){ } fail(); 7 fakeFileResourceFileSystemResource ClassPathResourceDefaultResourceLoader 8 getResourceByPath(String) URLUrlResource 9 FileSystemResourceLoader DefaultResourceLoadergetResourceByPath(String) org.springframework.core.io.FileSystemResourceLoader Default- 10 ResourceLoader getResourceByPath(String) FileSystemResource5-311 5-3 FileSystemResourceLoader12public void testResourceTypesWithFileSystemResourceLoader(){ResourceLoader resourceLoader = new FileSystemResourceLoader();13Resource fileResource = resourceLoader.getResource("D:/spring21site/README");assertTrue(fileResource instanceof FileSystemResource);assertTrue(fileResource.exists()); 14Resource urlResource = resourceLoader.getResource("file:D:/spring21site/README"); }assertTrue(urlResource instanceof UrlResource); 15FileSystemResourceLoader ResourceLoader FileSystemXmlApplication- ContextgetResourceByPath(String) DefaultResourceLoader16 FileSystemResource 2. ResourcePatternResolver ResourceLoader17 93. 88Spring IoC ResourcePatternResolverResourceLoaderResourceLoader Resource ResourcePatternResolver Resource org.springframework.core.io.support.ResourcePattern- Resolverpublic interface ResourcePatternResolver extends ResourceLoader { String CLASSPATH_ALL_URL_PREFIX = "classpath*:"; Resource[] getResources(String locationPattern) throws IOException;}ResourcePatternResolver ResourceLoader Resource[] getResources(String)Resources classpath*:ResourcePatternResolver org.springframework.core.io.support. PathMatchingResourcePatternResolverResourceLoader Ant**/*.suffixResourcePatternResolver classpath*: PathMatchingResourcePatternResolverResourceLoader PathMatchingResourcePatternResolver Default- ResourceLoaderPathMatchingResourcePatternResolver ResourceLoader ResourceLoaderPath- MatchingResourcePatternResolverDefaultResourceLoader ResourceResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();Resource fileResource = resourceResolver.getResource("D:/spring21site/README");assertTrue(fileResource instanceof ClassPathResource);assertFalse(fileResource.exists());...ResourceLoaderPathMatchingResourcePatternResolver DefaultResourceLoader5-4 FileSystemResourceLoader DefaultResourceLoader PathMatching- ResourcePatternResolverFileSystemResourceLoader5-4 DefaultResourceLoaderPathMatchingResourcePatternResolverpublic void testResourceTypesWithPathMatchingResourcePatternResolver(){ ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); Resource fileResource = resourceResolver.getResource("D:/spring21site/README"); assertTrue(fileResource instanceof ClassPathResource); assertFalse(fileResource.exists()); resourceResolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());fileResource = resourceResolver.getResource("D:/spring21site/README");assertTrue(fileResource instanceof FileSystemResource);assertTrue(fileResource.exists());} 3. 94. 5.1 89 Spring5-12345 5-1 ResourceResourceLoader 65.1.3 ApplicationContextResourceLoader 7 ApplicationContext ApplicationContext8 ApplicationContext 4-2ApplicationContextResourcePatternResolver ResourceLoaderApplicationContext 9 ResourceLoaderResourcePatternResolver ApplicationContextSpring 10 ApplicationContext org.springframework. context.support.AbstractApplicationContext Application- 11 Context ResourceLoader AbstractApplicationContext DefaultRe- sourceLoadergetResource(String)DefaultResourceLoader ResourcePatternResolverResource[]getResources (String) 12 AbstractApplicationContextAbstractApplicationContext resourcePatternResolverResourcePatternResolver 13 PathMatchingResourcePatternResolver PathMatchingResourcePattern- ResolverResourceLoaderAbstractApplicationContext DefaultResourceLoaderApplicationContext 14 ResourceLoader ResourcePatternResolver Application- ContextSpringApplicationContextResource- 15 Loader ResourcePatternResolver PathMatchingResource- PatternResolverDefaultResourceLoader5-2AbstractApplicationContext 16 ResourceLoaderResourcePatternResolver17 95. 90 Spring IoC 5-2 AbstractApplicationContextResourceLoaderResourcePatternResolverResourceLoaderResourcePatternResolverApplica- tionContext 1. ResourceLoader ApplicationContextResourceLoaderResourcePatternResolver ApplicationContextSpringResource ResourceLoaderApplicationContext 5-5ApplicationContext5-5 ResourceLoaderApplicationContextResourceLoader resourceLoader = new ClassPathXmlApplicationContext("");// // ResourceLoader resourceLoader = new FileSystemXmlApplicationContext("");Resource fileResource = resourceLoader.getResource("D:/spring21site/README");assertTrue(fileResource instanceof ClassPathResource);assertFalse(fileResource.exists());Resource urlResource2 = resourceLoader.getResource("http://www.spring21.cn");assertTrue(urlResource2 instanceof UrlResource); 2. ResourceLoader beanResourceLoader ResourceLoaderbean setterbean SpringAPISpring 96. 5.1 914.4.3 ApplicationContext Aware Resource- LoaderAwareApplicationContextAware 5-62 5-6 ResourceLoaderpublic class FooBar { private ResourceLoader resourceLoader; 3public void foo(String location){System.out.println(getResourceLoader().getResource(location).getClass()); 4} public ResourceLoader getResourceLoader() {return resourceLoader;5}public void setResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader; 6}} ResourceLoaderResource- 7 LoaderDefaultResourceLoader 89 10 ApplicationContextResourceLoader resourceLoader ApplicationContext Resource-11 LoaderResourceLoaderAwareApplicationContextAware FooBarSpringAPI12 FooBar ResourceLoaderAware Application-13 ContextAware5-75-7 ResourceLoaderAwareApplicationContextAware14public class FooBar implements ResourceLoaderAware{ private ResourceLoader resourceLoader; public void foo(String location)15{System.out.println(getResourceLoader().getResource(location).getClass());} 16public ResourceLoader getResourceLoader() {return resourceLoader;} 17 97. 92Spring IoC public void setResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader;}}public class FooBar implements ApplicationContextAware{ private ResourceLoader resourceLoader; public void foo(String location){System.out.println(getResourceLoader().getResource(location).getClass());} public ResourceLoader getResourceLoader() {return resourceLoader;}public void setApplicationContext(ApplicationContext ctx) throws BeansException {this.resourceLoader = ctx;}} FooBarbeanApplicationContext FooBarApplicationContextAware ResourceLoader ResourceLoader- AwareApplicationContextAware 3. Resource bean SpringPropertyEditors PropertyEditor BeanFactory org.springframework.core.io.Resource Property- EditorResourcebeanPropertyEditor BeanFactory ApplicationContext Application- ContextResource XMailerResource XMailer5-85-8 ResourceXMailerpublic class XMailer { private Resource template; public void sendMail(Map mailCtx){// String mailContext = merge(getTemplate().getInputStream(),mailCtx);//...} public Resource getTemplate() {return template; 98. 5.1 93 } public void setTemplate(Resource template) {this.template = template;}} 2 beanStringtemplate ApplicatonContext3 ...4 5ApplicationContext org.springframework.beans.support.Resource- EditorRegistrar Spring Resource PropertyEditor PropertyEditor org.springframework.core.io.ResourceEditor Application- 6 Context Resource ResourceEditor ApplicationContextResourceLoader 7 ResourceApplicationContextResourceEditor 8 Spring org.springframework.core.io.support.ResourceArrayProperty-EditorCustomEditorConfigurar 9 4. ApplicationContextResource ApplicationContextResourceLoader 10 ApplicationContextClassPathXmlApplicationContext FileSystemXmlApplicationContextApplicationContext 11 URLfile:http:ftp: SpringUrlResourceURL12 SpringResourceLoader classpath:ResourcePatternResolverclasspath*: Springclasspath13// ResourceLoader resourceLoader = new FileSystemXmlApplicationContext("classpath:conf/container-conf.xml"); 14// classpath:resource/template.vm15 classpath*:classpath:classpath16 ApplicationContext ClassPathXmlApplicationContextFileSystemXmlApplicationContext 17 99. 94Spring IoC ClassPathXmlApplicationContext classpath:classpath*:classpathbean ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:conf/appContext.xml"); FileSystemXmlApplicationContext conf/ appContext.xmlbeanApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml"); classpath: FileSystemXmlApplicationContextclasspathbeanApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml"); FileSystemXmlApplicationContextClasspath ClassPathResource FileSystem- ResourceFileSystemXmlApplicationContextorg.springfra- mework.core.io.FileSystemResourceLoaderDefaultResourceLoadergetRes- ourceByPath(String) FileSystemResourceLoaderApplicationContextbean ResourceLoader ApplicationContextClassPathXmlApplicationContext Classpath ClassPathXmlApplicationContext Classpath FileSystemXmlApplicationContext FileSystemXmlApplicationContext classpath:FileSystemXmlApplicationContext classpath: FileSystemXmlApplicationContextClasspath classpath:FileSystemXmlApplicationContext FileSystemXmlApplicationContextclasspath: Classpathbeanbean 100. 5.2 I18nF F MessageSource 95 ResourceLoaderclasspath: FileSystemXmlApplicationContext Classpath FileSystemXmlApplicationContext 2 FileSystemResource Spring 3 5.2 I18n MessageSource 4 5 5.2.1 Java SE 6 JavaI18nOReillyJava7 InternationalizationSpring 8Java java.util.Localejava.util.ResourceBundle1. LocaleLocaleLocale 9 ISOLocale.CHINA zh_CNLocale.USen_US10 Locale.ENGLISHenLocale Locale(String language) 11 Locale(String language, String country) Locale(String language, String country, String variant)Locale 12 Locale china = new Locale("zh","CN"); Locale.CHINA 13 LocaleLocale Locale 14 2. ResourceBundle 15 ResourceBundleLocaleString ResourceBundlebasename Locale basename 16 InternationalizationIn18I18n 17 101. 96 Spring IoC propertiespropertiesmessages.propertiesmessages_zh.propertiesmessages_zh_CN.propertiesmessages_en.propertiesmessages_en_US.properties...messagesResourceBundlebasename basenameLocale Locale# messages_zh_CN.propertiesmenu.file=({0})menu.edit=... # messages_en_US.propertiesmenu.file=File({0})menu.edit=Edit... propertiesISO-8859-1message_zh_ CN.propertiesnative2ascii ResourceBundle ResourceBundle getBundle (String baseName, Locale locale)LocaleResourceBundle Locale ResourceBundleLocale5.2.2 MessageSourceApplicationContextSpring Java SE org.springframework.context.MessageSourcepublic interface MessageSource {String getMessage(String code, Object[] args, String defaultMessage, Locale locale);String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException;String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessage zException; } Locale LocaleResourceBundleResourceBundle MessageSource String getMessage(String code, Object[] args, String defaultMessage, Locale locale)codeLocale 102. 5.2 I18nF F MessageSource 97defaultMessage String getMessage(String code, Object[] args, Locale locale) throws NoSuch- MessageException NoSuchMessageException2 String getMessage(MessageSourceResolvable resolvable, Locale locale) throws- NoSuchMessageExceptionMessageSourceResolvable3 MessageSourceResolvable MessageSourceResolvable NoSuchMessageException4 ApplicationContextResourceLoader MessageSourceApplicationContextResourceLoader5 ResourceLoaderApplicationContextMessageSource ApplicationContext messageSource Message-6 SourceMessageSourceMessageSource ApplicationContextStaticMessageSource 7 5-9 5-9 ApplicationContextmessageSource 89messageserrorcodes 10 ...11ApplicationContextLocale12ApplicationContext ctx = ...;String fileMenuName = ctx.getMessage("menu.file", new Object[]{"F"}, Locale.US);String editMenuName = ctx.getMessage("menu.file", null, Locale.US);assertEquals("File(F)", fileMenuName);13assertEquals("Edit", editMenuName); 1. MessageSource SpringMessageSource StaticMessageSource ResourceBundleMessage-14 SourceReloadableResourceBundleMessageSource org.springframework.context.support.StaticMessageSourceMessageSource 15 org.springframework.context.support.ResourceBundleMessageSource 16java.util.ResourceBundleMessageSource AbstractMessageSourceResourceBundleMessageFormat17 103. 98Spring IoC MessageSourceorg.springframework.context.support.ReloadableResourceBundleMessageSource java.util.ResourceBundle MessageSource cacheSecondspropertiespropertiesResourceBundleMessageSourceResourceLoader ReloadableResourceBundleMessageSource classpath ReloadableResourceBundle-MessageSourceJavadoc Standalone ApplicationContext5-10MessageSource 5-10 MessageSourceStaticMessageSource messageSource = new StaticMessageSource();messageSource.addMessage("menu.file", Locale.US, "File");messageSource.addMessage("menu.edit", Locale.US, "Edit");assertEquals("File(F)", messageSource.getMessage("menu.file", new Object[]{"F"}, Locale.US));assertEquals("Edit", messageSource.getMessage("menu.edit", null,"Edit", Locale.US)); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasenames(new String[]{"conf/messages"});// classpathassertEquals("File(F)", messageSource.getMessage("menu.file", new Object[]{"F"}, Locale.US)); ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();messageSource.setBasenames(new String[]{"file:conf/messages"}); // assertEquals("File(F)", messageSource.getMessage("menu.file", new Object[]{"F"},Locale.US)); ApplicationContext messageSource Message- Source5-35-3 MessageSource MessageSource Abstract- 104. 5.2 I18nF F MessageSource 99MessageSourceMessageSource 2. MessageSourceAwareMessageSourceApplicationContextMessageSourceAwarebean 2 MessageSource MessageSourceAwareApplicationContext3 ApplicationContext MessageSource setterbeanApplicationContext 4 messageSourceValidator MessageSource MessageSource 5 ApplicationContextmessageSource5-11 6 5-11 MessageSourceValidatorpublic class Validator{ 7 private MessageSource messageSource; public ValidateResult validate(Object target){8// // messageSource.getMessage(...)// return result9}public MessageSource getMessageSource(){return messageSource; 10}public void setMessageSource(MessageSource msgSource){this.messageSource = msgSource;11}// ...} 1213 messages 14errorcodes 1516... 17 105. 100 Spring IoC MessageSourceApplicationContext Standalone Application MessageSourceWebApplicationContext Viewtag ApplicationContext5.3 SpringApplicationContextJava SE Java SE 5.3.1 Java SECustom Event publication java.util.Eve- ntObjectjava.util.EventListenerEventObject EventListener define your own event object java.util.EventObject 5-125-12 public class MethodExecutionEvent extends EventObject {private static final long serialVersionUID = -71960369269303337L;private String methodName;public MethodExecutionEvent(Object source) { super(source); } public MethodExecutionEvent(Object source,String methodName) { super(source); this.methodName = methodName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } }MethodExecutionEvent EventObject define custom event listener MethodExecutionEvent 106. 5.3 101 5-13 MethodExecutionEvent5-13 MethodExecutionEventListener 2public interface MethodExecutionEventListener extends EventListener { /*** MethodExecutionEvent*/ 3 void onMethodBegin(MethodExecutionEvent evt); /*** MethodExecutionEvent 4*/ void onMethodEnd(MethodExecutionEvent evt);} 5java.util.EventListener MethodExecutionEvent 6 7 5-145-14 SimpleMethodExecutionEventListener 8public class SimpleMethodExecutionEventListener implements MethodExecutionEventListener { 9public void onMethodBegin(MethodExecutionEvent evt) {String methodName = evt.getMethodName();System.out.println("start to execute the method["+methodName+"].");}10public void onMethodEnd(MethodExecutionEvent evt) {String methodName = evt.getMethodName(); 11System.out.println("finished to execute the method["+methodName+"].");}} 12 EventPublisher 5-1513 MethodExecutionEvent5-15 MethodExeuctionEventPublisher 14public class MethodExeuctionEventPublisher { private List listeners = new 15ArrayList(); public void methodToMonitor()16{MethodExecutionEvent event2Publish = new MethodExecutionEvent(this,"methodToMonitor");publishEvent(MethodExecutionStatus.BEGIN,event2Publish); 17 107. 102 Spring IoC // // ...publishEvent(MethodExecutionStatus.END,event2Publish);} protected void publishEvent(MethodExecutionStatus status, MethodExecutionEvent methodExecutionEvent) {List copyListeners = new ArrayList(listeners);for(MethodExecutionEventListener listener:copyListeners){ if(MethodExecutionStatus.BEGIN.equals(status)) listener.onMethodBegin(methodExecutionEvent); else listener.onMethodEnd(methodExecutionEvent);}} public void addMethodExecutionEventListener(MethodExecutionEventListener listener){this.listeners.add(listener);}public void removeListener(MethodExecutionEventListener listener){if(this.listeners.contains(listener)) this.listeners.remove(listener);}public void removeAllListeners(){this.listeners.clear();} public static void main(String[] args) {MethodExeuctionEventPublisher eventPublisher = new MethodExeuctionEventPublisher();eventPublisher.addMethodExecutionEventListener(new SimpleMethodExecutionEventListener());eventPublisher.methodToMonitor();}} methodToMonitor()MethodExeuction- EventPublisher MethodExecutionEvent MethodExecutionEventListener safe-copy MethodExeuctionEventPublisher remove MethodExeuctionEventPublisher MethodExeuctionEventPublisher 108. 5.3 103Java SE 5-4 2 3 4 5 6 75-4 85.3.2 Spring 9 Spring ApplicationContext org.springframework.context.Appli- cationEvent org.springframework.context.Application- 10 ListenerbeanApplicationContext ApplicationEventApplicationEvent ApplicationListener11 ApplicationEvent 12 Springjava.util.EventObject Spring ContextClosedEventApplicationContext13 ContextRefreshedEventApplicationContext14 RequestHandledEventWebServletRequestHandled-EventJava EEServlet15 ApplicationListenerApplicationContext java.util.Event- ListenerApplicationContextEventListenerbean16 EventListener ApplicationContext 17 109. 104 Spring IoC ApplicationContextResourceLoaderMessageSour