Spring-Context之三:使用XML和Groovy DSL配置Bean

简介: 在第一讲中显示了如何使用注解配置bean,其实这是Spring3引进的特性,Spring2使用的是XML的方式来配置Bean,那时候漫天的XML文件使得Spring有着配置地狱的称号。Spring也一直在力求改变这一缺陷。

在第一讲中显示了如何使用注解配置bean,其实这是Spring3引进的特性,Spring2使用的是XML的方式来配置Bean,那时候漫天的XML文件使得Spring有着配置地狱的称号。Spring也一直在力求改变这一缺陷。Spring3引入的注解方式确实使配置精简不少,而Spring4则引入了Groovy DSL来配置,其语法比XML要简单很多,而且Groovy本身是门语言,其配置文件就相当于代码,可以用来实现复杂的配置。

废话少说,让我们来对Groovy DSL配置来个第一次亲密接触。

首先我们先实现一个XML的bean配置,沿用第一讲中的例子。

configuration.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="movieService" class="huangbowen.net.service.DefaultMovieService"/>

    <bean id="cinema" class="huangbowen.net.service.Cinema">
        <property name="movieService" ref="movieService"/>
    </bean>
</beans>

这个XML文件就不用我多做解释了,很清晰明了。Ok,照例写个测试来测一下。

XmlConfigurationTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package huangbowen.net;

import huangbowen.net.service.Cinema;
import huangbowen.net.service.DefaultMovieService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/configuration.xml"})
public class XmlConfigurationTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private Cinema cinema;

    @Test
    public void shouldGetCinemaInstance()  {
        Cinema cinema = applicationContext.getBean(Cinema.class);
        assertNotNull(cinema);
    }

    @Test
    public void shouldGetAutowiredCinema() {
        assertNotNull(cinema);
    }

    @Test
    public void shouldGetMovieServiceInstance() {
        assertNotNull(cinema.getMovieService());
        assertThat(cinema.getMovieService(), instanceOf(DefaultMovieService.class));
    }


}

这个测试与第二讲中的测试基本上一样,不过Spring配置的读取是从configuration.xml来的,在@ContextConfiguration中指定了该xml文件为Spring配置文件。

如果想使用Groovy DSL的话第一步需要引入groovy依赖。

pom.xml
1
2
3
4
5
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.2.2</version>
</dependency>

然后就可以新建一个groovy文件来实现配置编写。

Configuration.groovy
1
2
3
4
5
6
7
beans {

   movieService huangbowen.net.service.DefaultMovieService

   cinema huangbowen.net.service.Cinema, movieService : movieService

}

这其实体现不出来Groovy DSL的强大灵活,因为我们的例子太简单了。

beans相当于xml中的beans标签,第一行中是 bean id + class的形式。 第二行是bean id + class + properties map的形式。第二个参数是一个map数组,分别对应property和值。

实现同样的Bean配置有很多种写法。

1
2
3
movieService (huangbowen.net.service.DefaultMovieService)

cinema(huangbowen.net.service.Cinema, {movieService : movieService})

上面这种其实是Groovy语法的一个特性,在调用方法时括号是可选的,既可以加,也可以不加。

1
2
3
4
5
movieService huangbowen.net.service.DefaultMovieService

cinema (huangbowen.net.service.Cinema) {
    movieService :ref movieService
}

上面这中使用了另一个设置属性的方法,通过一个闭包将属性设置进去。

1
2
3
4
5
movieService huangbowen.net.service.DefaultMovieService

cinema (huangbowen.net.service.Cinema) {
    movieService : movieService
}

这种更好理解了,ref方法也是可选的。

来照旧写个测试来测一下。

GroovyDSLConfigurationTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package huangbowen.net;

import huangbowen.net.service.Cinema;
import huangbowen.net.service.DefaultMovieService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AbstractGenericContextLoader;

import static huangbowen.net.GroovyDSLConfigurationTest.*;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:Configuration.groovy", loader = GenericGroovyContextLoader.class)
public class GroovyDSLConfigurationTest {

    public static class GenericGroovyContextLoader extends
            AbstractGenericContextLoader {

        @Override
        protected BeanDefinitionReader createBeanDefinitionReader(
                GenericApplicationContext context) {
            return new GroovyBeanDefinitionReader(context);
        }

        @Override
        protected String getResourceSuffix() {
            return ".groovy";
        }

    }

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private Cinema cinema;

    @Test
    public void shouldGetCinemaInstance()  {
        Cinema cinema = applicationContext.getBean(Cinema.class);
        assertNotNull(cinema);
    }

    @Test
    public void shouldGetAutowiredCinema() {
        assertNotNull(cinema);
    }

    @Test
    public void shouldGetMovieServiceInstance() {
        assertNotNull(cinema.getMovieService());
        assertThat(cinema.getMovieService(), instanceOf(DefaultMovieService.class));
    }


}

在集成测试中如果加载xml配置文件,Spring提供了GenericXmlContextLoader类,如果加载注解方式的配置类,Spring提供了AnnotationConfigContextLoader类。但是对于Groovy配置文件Spring testContext框架还未提供相应的Loader,所以在本测试方法中需要自己实现一个Loader,其实也简单,只要实现两个方法即可。

本例中的源码请在我的GitHub上自行下载。

相关文章
|
9月前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
2140 1
|
10月前
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
668 26
|
9月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
460 0
|
12月前
|
XML Java 数据格式
【SpringFramework】Spring IoC-基于XML的实现
本文主要讲解SpringFramework中IoC和DI相关概念,及基于XML的实现方式。
253 69
|
8月前
|
安全 Java 数据安全/隐私保护
深入探讨 Spring Security 中的 DSL 设计
本文深入解析了 Spring Security 中的 DSL(领域特定语言)设计,探讨其在安全规则定义中的应用。文章首先介绍了 DSL 的基本概念及其分类,随后分析了 Spring Security 中配置 DSL、表达式 DSL 和用户构建 DSL 的实现与优势。这些 DSL 不仅简化了复杂安全规则的配置,还提升了代码的可读性和开发效率。最后,文章总结了 DSL 在降低复杂性、增强灵活性和适配复杂场景中的重要作用,为开发者提供了学习和实践的方向。
232 0
|
12月前
|
XML Java 数据格式
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
本文介绍了在使用Spring框架时,如何通过创建`applicationContext.xml`配置文件来管理对象。首先,在resources目录下新建XML配置文件,并通过IDEA自动生成部分配置。为完善配置,特别是添加AOP支持,可以通过IDEA的Live Templates功能自定义XML模板。具体步骤包括:连续按两次Shift搜索Live Templates,配置模板内容,输入特定前缀(如spring)并按Tab键即可快速生成完整的Spring配置文件。这样可以大大提高开发效率,减少重复工作。
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
|
12月前
|
存储 Java Spring
【Spring】获取Bean对象需要哪些注解
@Conntroller,@Service,@Repository,@Component,@Configuration,关于Bean对象的五个常用注解
317 12
|
12月前
|
存储 Java 应用服务中间件
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式
431 12
|
12月前
|
XML Java 数据格式
Spring容器Bean之XML配置方式
通过对以上内容的掌握,开发人员可以灵活地使用Spring的XML配置方式来管理应用程序的Bean,提高代码的模块化和可维护性。
365 6