Spring零xml配置使用详解

Spring零xml配置使用详解

1   概述

常规spring项目中,会采用纯xml或者xml和注解配合使用的配置方式。在spring 3.0版本以后就引入 @ConfigurationAnnotationConfigApplicationContext 等实现,可以支持纯java方式配置的spring 容器,不需要任何xml配置。本文介绍如何搭建一个零配置的spring 容器项目。

 

2   主要概念

2.1   @Configuration

我们定义一个java类后,使用@Configuration注解表示这个一个配置类,等同于xml配置中xml文件。

2.2  @Bean

在配置类中使用,等同于xml配置的<bean/>定义一个实例。类似下面样例代码,就定义myService实例。这样定义beanname默认就为方法名,样例即为myService。

@Configuration

public class AppConfig {

 

    @Bean

    public MyService myService() {

        return new MyServiceImpl();

    }

 

}

2.3  AnnotationConfigApplicationContext

有了配置类后,需要构建spring容器。在xml配置作为入口的项目中,会用ClassPathXmlApplicationContext 来构建容器,而在纯java类配置的场景中,AnnotationConfigApplicationContext承担了同样地构建容器实例的角色。下面代码就演示了如何基于AppConfig.java构建容器以及访问其中的bean实例。

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    MyService myService = ctx.getBean(MyService.class);
}

3   深入使用

3.1  @ComponentScan

类似xml配置中的component-scan我们可以配置针对特别package的扫描配置,自动将包内@Component、@Service 等注解的bean类给扫描出来,注入到容器中。用法如下:
@Configuration
@ComponentScan(basePackages = "com.acme")
public class AppConfig  {
    ...
}

3.2  @Bean的各类属性

name属性可以自定义bean的名字;initMethod指定了bean的初始化方法;destroyMethod指定实例销毁时的清理方法。
@Bean(name = "myFoo"initMethod = "init",destroyMethod = "cleanup")

默认的@Bean定义的实例都是单例,可以通过@Scope定义不同生命周期的bean

    @Bean
    @Scope("prototype")
    public Encryptor encryptor() {
        // ...
    }

3.3  @Import

大型项目中,我们可能会配置多个xml组合使用。纯Java配置中可以创建多个Config配置类后,在其中一个主配置类,通过@import引入其他配置类,最后构建容器时,提供这个主配置类即可。样例代码如下:

@Configuration
public class ConfigA {
 
     @Bean
    public A a() {
        return new A();
    }
 
}
 
@Configuration
@Import(ConfigA.class)
public class ConfigB {
 
    @Bean
    public B b() {
        return new B();
    }
 
}

3.4  调度任务以及属性注入等注解使用

在配置类,我们可以直接通过@EnableScheduling和@PropertySource("classpath:my.properties")等方式支持调度以及引入属性文件。注意使用@PropertySource引入属性文件时,需要同时定义一个PropertySourcesPlaceholderConfigurer的bean。 样例代码如下:

@Configuration
@ComponentScan(basePackages = "com.test")
@EnableScheduling
@PropertySource("classpath:my.properties")
public class AppConfig {
  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
  }
}

 

@Component
public class SheduledTask { 
  @Value("${api.hosts}")
  private String hosts;
  @Value("${api.port}")
  private String port;
 
  @Scheduled(cron = "0 0/10 * * * *")
  public void doStuff() {
        }
}

3.5  Web 容器实例

AnnotationConfigWebApplicationContext可以用来构建支持web mvc容器的配置。 如下配置web.xml的子配置即可引入零配置的web spring mvc应用。

<web-app>
    <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
        instead of the default XmlWebApplicationContext -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
 
    <!-- Configuration locations must consist of one or more comma- or space-delimited
        fully-qualified @Configuration classes. Fully-qualified packages may also be
        specified for component-scanning -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.acme.AppConfig</param-value>
    </context-param>
 
    <!-- Bootstrap the root application context as usual using ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Declare a Spring MVC DispatcherServlet as usual -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext
            instead of the default XmlWebApplicationContext -->
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <!-- Again, config locations must consist of one or more comma- or space-delimited
            and fully-qualified @Configuration classes -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.acme.web.MvcConfig</param-value>
        </init-param>
    </servlet>
 
    <!-- map all requests for /app/* to the dispatcher servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>
</web-app>

 

4   总结

如上所述,基于@ConfigurationAnnotationConfigApplicationContext等实现可以零配置构建spring容器应用以及spring mvn web应用,常见的注解使用方式都可以组合使用。基于纯java类配置的详细文档可以参考官方文档。spring基于纯java类的配置官方文档链接

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值