Spring 4: Groovy DSL bean definition

#Spring 4: Groovy DSL bean definition

In Spring 2.x, script language is supported in Spring via the Java scripting engine.

In Spring 4.0, Groovy is a first class citizen in Spring. Groovy can be used as an alternative for bean definition.

Groovy DSL bean definition

As a Spring developer, you could be very familiar with XML and annotation for bean definition.

An example of XML bean definition.

<pre> &lt;jdbc:embedded-database id="dataSource" type="H2"> &lt;/jdbc:embedded-database> &lt;bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> &lt;property name="persistenceUnitName" value="persistenceUnit" /> &lt;property name="dataSource" ref="dataSource" /> &lt;property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence">&lt;/property> &lt;property name="packagesToScan"> &lt;array> &lt;value>com.hantsylabs.example.spring.model&lt;/value> &lt;/array> &lt;/property> &lt;property name="jpaProperties"> &lt;value> hibernate.format_sql=true hibernate.show_sql=true hibernate.hbm2ddl.auto=create &lt;/value> &lt;/property> &lt;/bean> &lt;bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> &lt;property name="entityManagerFactory" ref="entityManagerFactory" /> &lt;/bean> </pre>

The following is the equivalent bean definition based on Java annotation.

<pre> @Configuration @ComponentScan(basePackages = { "com.hantsylabs.example.spring.dao", "com.hantsylabs.example.spring.jpa" }) @EnableTransactionManagement(mode=AdviceMode.ASPECTJ) public class JpaConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource()); emf.setPackagesToScan("com.hantsylabs.example.spring.model"); emf.setPersistenceProvider(new HibernatePersistence()); emf.setJpaProperties(jpaProperties()); return emf; } private Properties jpaProperties() { Properties extraProperties = new Properties(); extraProperties.put("hibernate.format_sql", "true"); extraProperties.put("hibernate.show_sql", "true"); extraProperties.put("hibernate.hbm2ddl.auto", "create"); return extraProperties; } @Bean public PlatformTransactionManager transactionManager() { return new JpaTransactionManager(entityManagerFactory().getObject()); } } </pre>

The following context defines these beans in a Groovy file.

<pre> import org.apache.commons.dbcp.BasicDataSource import org.springframework.orm.jpa.JpaTransactionManager import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean import com.hantsylabs.example.spring.jpa.JpaConferenceDaoImpl beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:spring4-sandbox" username = "sa" password = "" } entityManagerFactory(LocalContainerEntityManagerFactoryBean){ persistenceProviderClass="org.hibernate.ejb.HibernatePersistence" dataSource=dataSource persistenceUnitName="persistenceUnit" packagesToScan=["com.hantsylabs.example.spring.model"] jpaProperties=[ "hibernate.format_sql":"true", "hibernate.show_sql":"true", "hibernate.hbm2ddl.auto":"create" ] } transactionManager(JpaTransactionManager){ entityManagerFactory=entityManagerFactory } conferenceDao(JpaConferenceDaoImpl){ } } </pre>

If you have some experience of Grails, you could have recognized this feature is really a copy of Grails resources.groovy.

Add groovy dependency in your pom.xml.

<pre> &lt;dependency> &lt;groupId>org.codehaus.groovy&lt;/groupId> &lt;artifactId>groovy-all&lt;/artifactId> &lt;version>2.1.8&lt;/version> &lt;/dependency> </pre>

Write some test codes.

<pre> @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "classpath:/com/hantsylabs/example/spring/config/JpaConfigGroovy.groovy", loader = GenericGroovyContextLoader.class) @TransactionConfiguration public class GroovyJpaConferenceDaoImplTest { public static class GenericGroovyContextLoader extends AbstractGenericContextLoader { @Override protected BeanDefinitionReader createBeanDefinitionReader( GenericApplicationContext context) { return new GroovyBeanDefinitionReader(context); } @Override protected String getResourceSuffix() { return ".groovy"; } } // test codes } </pre>

I've tried to load the Groovy bean definition resource through @ContextConfiguration annotation, but it does not work. By default, the locations and value are ready for loading XML bean definition. Spring 4.0 includes a GroovyBeanDefinitionReader for reading and parsing Groovy bean definition. It is easy to write a custom context loader for loading the Groovy bean definition.

The Conference, ConferenceDao, JpaConferneceDaoImpl, and the CRUD test cases are no difference from my before posts.

##Create Spring Bean in Groovy way

Create a simple ConferenceService bean, but use Groovy, put it under src/main/groovy folder.

<pre> package com.hantsylabs.example.spring.service import com.hantsylabs.example.spring.dao.ConferenceDao class ConferenceService { def conferenceDao def findConferenceBySlug(String slug) { conferenceDao.findBySlug(slug) } } </pre>

Declare it as a Spring bean.

<pre> conferenceService(ConferenceService){ conferenceDao=conferenceDao } </pre>

Test it.

<pre> package com.hantsylabs.example.spring.dao; //other imports are omitted import com.hantsylabs.example.spring.service.ConferenceService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "classpath:/com/hantsylabs/example/spring/config/JpaConfigGroovy.groovy", loader = GenericGroovyContextLoader.class) @TransactionConfiguration public class GroovyConferenceServiceTest { //all duplicated codes are omitted @Autowired ConferenceService conferenceService; @Test @Transactional public void retrieveConference() { //all duplicated codes are omitted // query by slug conference = (Conference) conferenceService.findConferenceBySlug("jud-2013"); assertTrue(conference != null); } } </pre>

Groovy files are put in src/main/groovy, you need to configure the java compiler to compile groovy files.

<pre> &lt;plugin> &lt;artifactId>maven-compiler-plugin&lt;/artifactId> &lt;!-- 2.8.0-01 and later require maven-compiler-plugin 3.1 or higher --> &lt;version>3.1&lt;/version> &lt;configuration> &lt;compilerId>groovy-eclipse-compiler&lt;/compilerId> &lt;!-- set verbose to be true if you want lots of uninteresting messages --> &lt;!-- &lt;verbose>true&lt;/verbose> --> &lt;/configuration> &lt;dependencies> &lt;dependency> &lt;groupId>org.codehaus.groovy&lt;/groupId> &lt;artifactId>groovy-eclipse-compiler&lt;/artifactId> &lt;version>2.8.0-01&lt;/version> &lt;/dependency> &lt;!-- for 2.8.0-01 and later you must have an explicit dependency on groovy-eclipse-batch --> &lt;dependency> &lt;groupId>org.codehaus.groovy&lt;/groupId> &lt;artifactId>groovy-eclipse-batch&lt;/artifactId> &lt;version>2.1.8-01&lt;/version> &lt;!-- or choose a different compiler version --> &lt;!-- &lt;version>1.8.6-01&lt;/version> --> &lt;!-- &lt;version>1.7.10-06&lt;/version> --> &lt;/dependency> &lt;/dependencies> &lt;/plugin> &lt;plugin> &lt;groupId>org.codehaus.mojo&lt;/groupId> &lt;artifactId>build-helper-maven-plugin&lt;/artifactId> &lt;version>1.5&lt;/version> &lt;executions> &lt;execution> &lt;id>add-source&lt;/id> &lt;phase>generate-sources&lt;/phase> &lt;goals> &lt;goal>add-source&lt;/goal> &lt;/goals> &lt;configuration> &lt;sources> &lt;source>src/main/groovy&lt;/source> &lt;/sources> &lt;/configuration> &lt;/execution> &lt;execution> &lt;id>add-test-source&lt;/id> &lt;phase>generate-test-sources&lt;/phase> &lt;goals> &lt;goal>add-test-source&lt;/goal> &lt;/goals> &lt;configuration> &lt;sources> &lt;source>src/test/groovy&lt;/source> &lt;/sources> &lt;/configuration> &lt;/execution> &lt;/executions> &lt;/plugin> </pre>

build-helper-maven-plugin plugin will add src/main/groovy as a compilation source folder, and compiler plugin with groovy-eclipse-compiler configuration will compile groovy into java classes.

If you are using Eclispe or Spring ToolSuite, do not forget install Grails/Groovy plugin from SpringSource, or download a copy of SpringSource Grails/Groovy Suite for groovy development.

##Sample codes

The samples codes is hosted on my github.com account.

https://github.com/hantsy/spring4-sandbox

转载于:https://my.oschina.net/hantsy/blog/184643

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值