spring框架之javaconfig

时间:2023-03-08 22:53:04
spring框架之javaconfig

简介:随着java5的推出,加上当年基于纯java annotation的依赖注入框架Guice的出现,spring推出并持续完善了基于java代码和annotation元信息的依赖关系绑定描述方法,即javaconfig项目

基于javaconfig方式的依赖关系绑定描述基本上映射了最早的基于XML的配置方式

一、表达形式层面

基于xml的配置方式是这样的

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

      xmlns:context="http://www.springframework.org/schema/context"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context.xsd

    http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans.xsd  >

<!- bean定义 ->

</beans>

而基于javaconfig的配置方式是这样的

@configuration

public class MockConfiguration{

  //bean定义

}

任何一个标注了@configuration的java类定义都是一个javaconfig的配置类

二、1.注册bean定义层面基于xml的配置方式是这样的

<bean id="mockService" class="...MockServiceImpl">

  ...

</bean>而基于javaconfig的配置方式是这样的

@configuration

public class MockConfiguration{

  @Bean

  public MockService mockService(){

    return new MockServiceImpl():

  }

}

任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,方法 名将默认成为该bean定义的id。

2.批量定义注册bean基于xml的配置方式是这样的

<context:component-scan base-package="..."/>

配合@Component和@Repository等,将标注了这些元信息annotation的bean定义类批量采集到spring的IoC容器中而基于javaconfig的配置方式是这样的

@ComponentScan(String[] basePackages

注:@ComponentScan是springboot框架一个关键组件

四、表达依赖注入关系层面基于xml的配置方式是这样的

<bean id="mockService" class="...MockServiceImpl">

  <property name="dependencyService" ref="dependencyService">

</bean>

<bean id="dependencyService" class="...dependencyServiceImpl"/>

而基于javaconfig的配置方式是这样的

@configuration

public class MockConfiguration{

  @Bean

  public MockService mockService(){

    return new MockServiceImpl(dependencyService()):

  }

  @Bean

  public DependencyService dependencyService(){

    return new DependencyServiceImpl():

  }

}

如果一个bean依赖其他bean,则直接调用对应javaconfig类中依赖bean的创建方法就可以了