了解一点儿JavaConfig
Java 5 的推出,加上当年基于纯Java Annotation的依赖注入框架Guice的出现,使得Spring框架及其社区也“顺应民意”,推出并持续完善了基于Java代码和Annotation元信息的依赖关系绑定描述方式,即JavaConfig项目。
基于JavaConfig方式的依赖关系绑定描述基本上映射了最早的基于XML的配置方式,比如:
(1)表达形式层面
基于XML的配置方式是这样的:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"> <!--bean定义--> </beans>
而基于JavaConfig的配置方式是这样的:
@Configuration public class MockConfiguration{ //bean定义 }
任何一个标注了@Configuration的Java类定义都是一个JavaConfig配置类。
(2)注册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。
(3)表达依赖注入关系层面
为了表达bean与bean之间的依赖关系,在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的创建方法就可以了。