Skip to main content
mustafa daşgınmdasgin.blogspot.commustafa.dasgin@prime.com.trSpring
Expert One-on-One J2EE Design and Development	(Rod Johnson)Sıradan Java sınıflarına yetenekler kazandırır.Transactions, Monitoring, Concurrency, RemotingBağımlılık aktarımını üstlenirModüler yapılıCoreVeri erişimi/entegrasyonuWebAOPTestSpring’e Giriş
Spring Modülleri
Konfigürasyona göre “bean” yaratıp yönetimini üstlenirXML tabanlıNotlandırma (Annotation) tabanlıJava tabanlıorg.springframework.context.ApplicationContext ClassPathXmlApplicationContextFileSystemXmlApplicationContextXmlWebApplicationContextAnnotationConfigApplicationContextAnnotationConfigWebApplicationContextIoC Container
IoC Container (Devam)
XML Tabanlı Konfigürasyon<beans xmlns=“...><bean id=“userService" class=“com.prime.UserServiceImpl"> <property name=“userDao" ref=“userDao"/><!– diger ek tanımlamalar --></bean><bean id=“userDao" class=“com.prime.UserDaoImpl"><!– diger ek tanımlamalar --></bean></beans
Notlandırma Tabanlı Konfig.<beans xmlns=“...><context:component-scan base-package="org.example"/></beans>@Service //@Component@Scope("prototype")publicclassSimpleMovieLister { @Autowired//@ResourceprivateMovieFindermovieFinder;publicSimpleMovieLister(MovieFindermovieFinder) { this.movieFinder= movieFinder;}}@Repository //@ComponentpublicclassJpaMovieFinderimplementsMovieFinder { // implementation elided for clarity}
AnnotationConfigWebApplicationContextCGLIB jar gerekliJava Tabanlı Konfigürasyon@ConfigurationpublicclassAppConfig{@Bean(name = "myFoo",initMethod= "init")@Scope("prototype")publicFoofoo() { returnnewFoo(bar());} @Bean publicBar bar() { returnnewBar(); } }
IoC Container tarafından yaratılıp, bağımlılıkları ve yaşam döngüsü yönetilen basit Java nesneleri (POJO)Tanımlanırken;Sınıfıid ve/veya ismiScope değeriBağımlılıklarıYaşam döngüsü metotları belirtilebilir.Container 3 farklı yöntemle beanleri yaratır:Sınıfın yapıcısı (constructor)static factory metotinstance factory metotBean Nedir?
Yapıcı ileStatic Factory metot ileBean Yaratma Yöntemleri<bean id="exampleBean" class="examples.ExampleBean"/><bean id="clientService" class="examples.ClientFactoryService“factory-method="createClient"/>publicclassClientFactoryService { publicstaticClientServicecreateClient() { 	new ClientService(); }}
Instance Factory metot ileBean Yaratma Yöntemleri (Devam)<bean id="serviceLocator" class="examples.DefaultServiceLocator“/><bean id="clientService“factory-bean="serviceLocator“factory-method="createClientServiceInstance"/>publicclassDefaultServiceLocator { publicClientServicecreateClientServiceInstance() { returnnew ClientService();}}
Bean Scopeları<web-app>... <listener><listener-class> org.springframework.web.context.request.RequestContextListener</listener-class></listener> ...</web-app>
Singleton Scope
Prototype Scope
org.springframework.beans.factory.InitializingBeanorg.springframework.beans.factory.DisposableBeanBean Yaşam Döngüsü<bean id="exampleBean" class="examples.ExampleBean"/>publicclassExampleBeanimplementsInitializingBean, DisposableBean{ publicvoidafterPropertiesSet() {// do some initialization work}publicvoid destroy() { // do some destruction work}}
init-methoddestroy-methodBean Yaşam Döngüsü (Devam)<bean id="exampleBean" class="examples.ExampleBean" init-method="init“ destroy-method=“cleanup”/>publicclassExampleBean { publicvoid init() { // do some initialization work} publicvoid cleanup() { // do some destruction work}}
@PostConstruct@PreDestroyBean Yaşam Döngüsü (Devam)publicclassExampleBean {@PostConstructpublicvoidinit() { //...} @PreDestroypublicvoidcleanup() { //...}}
Yapıcı ile AktarımBağımlılık Aktarımıpackagex.y; publicclassFoo { publicFoo(Bar bar, Bazbaz) { // ...}}<beans> <bean id="foo" class="x.y.Foo"><constructor-arg ref="bar"/><constructor-arg ref="baz"/></bean><bean id="bar" class="x.y.Bar"/><bean id="baz" class="x.y.Baz"/></beans>
Yapıcı ile Aktarım (Devam..)Bağımlılık Aktarımı (Devam)<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/><constructor-arg index="1" value="42"/></bean><bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg name="years" value="7500000"/><constructor-arg name="ultimateanswer" value="42"/> </bean>
Setter Metotları ile AktarımBağımlılık Aktarımı (Devam..)<bean id="exampleBean" class="examples.ExampleBean“><property name="beanOne"><ref bean="anotherExampleBean"/></property><property name="beanTwo" ref="yetAnotherBean"/><property name="integerProperty" value="1"/></bean><bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Primitive Değerlerin Aktarımıpackageexamples;publicclassExampleBean { privateintyears;String ultimateAnswer; publicExampleBean(int years, String ultimateAnswer) {this.years= years;this.ultimateAnswer= ultimateAnswer;}}<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean>
Collection Yapıların Aktarımı<bean id="moreComplexObject" class="example.ComplexObject"><!-- java.util.Properties --><property name="adminEmails"><props><prop key="administrator">admin@expl.org</prop><prop key="support">support@expl.org</prop><prop key="dev">development@expl.org</prop> </props></property>	<!– java.util.List<property name="someList"><list><value>a list element</value><ref bean="myDataSource" /></list></property>
Collection Yapılarının Akt. (Devam)<!-- java.util.Map<property name="someMap"><map><entry key="entry" value="just some string"/><entry key ="a ref" value-ref="myDataSource"/></map></property><!-- java.util.Set --><property name="someSet"><set><value>just some string</value><ref bean="myDataSource" /></set></property></bean>
Null ve Boş String Aktarımı<!-- Boş String --><bean class="ExampleBean"><property name="email" value=""/></bean><!-- Null --><bean class="ExampleBean"><property name="email"><null/></property></bean>
Modları:byNamebyTypeconstructorPrimitive tipler için kullanılamazAynı tip değerinde birden fazla aday bean varsa hata oluşur.Autowire<bean id=“userService” class=“services.UserService” autowire=“byName”/>
web.xmlJSF ile Entegrasyon<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>...<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value></context-param>
faces-config.xmlApplicationContext erişimi:JSF ile Entegrasyon (Devam)<faces-config><application><el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>... </application></faces-config>ApplicationContextctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
Farklı transaction APIleri (JTA, JDBC, Hibernate, JPA) üzerine ortak bir model sunar.Transaction gerçekleştirimi değişse bile kodta değişiklik yapmaya gerek yok.Programlama veya tanımlama ile transaction tanımları yapılabilir.Basit APISpring Transaction Desteği
JDBC – DataSourceTransactionManagerJTA – JtaTransactionManagerHibernate – HibernateTransactionManagerJPA - JpaTransactionManagerPlatformTransactionManager<bean id=“txManager"           class="org.springframework.orm.jpa.JpaTransactionManager“<property name=“entityManagerFactory” ref="entityManagerFactory"/></bean><bean id=“entityManagerFactory“class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">	<property name=“dataSource” ref=“dataSource”/>	...</bean>
XML  ile Transaction Tanımlama<aop:config><aop:pointcut id="serviceOperation“expression="execution(* x.y.service..*Service.*(..))"/> <aop:advisorpointcut-ref="serviceOperation“advice-ref="txAdvice"/></aop:config><bean id="fooService" class="x.y.service.DefaultFooService"/><bean id="anotherService" class="org.xyz.SomeService"/><tx:advice id="txAdvice“transaction-manager="txManager" ><tx:attributes><tx:method name="get*" read-only="true"/><tx:method name="*"/></tx:attributes>
Notlandırma ile Transaction Tanım.@Transactional(readOnly = true)publicclassDefaultFooServiceimplementsFooService{publicFoogetFoo(String fooName) { // do something } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)publicvoidupdateFoo(Foofoo) { // do something } }<bean id="fooService" class="x.y.service.DefaultFooService"/> <tx:annotation-driven transaction-manager="txManager"/>
LocalEntityManagerFactoryBeanEntityManagerFactory’i JNDI’dan elde etmeLocalContainerEntityManagerFactoryBeanJPA Desteği
JPA Desteği (Devam)<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"/><property name="persistenceUnitName" value="simpleJpa"/><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="showSql" value="true"/><property name="generateDdl" value="true"/><property name="database" value="HSQL"/></bean></property></bean>
Spring Reference Documantationhttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/Kaynak