在傳統的Spring框架系列中,xml配置文件無處不在。有SpringMVC、dao、service等各層次的配置文件。到了目前SpringBoot的時代,XML文件幾乎銷聲匿跡。那么SpringBoot背后是如何做到無XML文件配置的呢?
首先,我們回顧一下在xml配置的時代,我們是如何定義一個Bean的?一般的,定義一個Bean的代碼片斷如下:
<bean id="myBean" class="cn.sessiontech.service.xxxServerImpl">
...
</bean>
如果要定義的Bean數量特別的多,那么還是一個個定義嗎?不太現實。故引出了context:component-scan。如:<context:component-scan base-package="cn.sessiontech" />,用於掃描那些被打上了特殊注解的類。將其批量的采集至SpringIoc容器中去。 base-package用於指定掃描范圍。
SpringBoot采用了叫JavaConfig方式來代替Xml配置,下邊分幾大點來比對其各自的表現形式。
1.配置形式層面上的。
xml方式:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<!--具體的bean定義-->
</beans>
JavaConfig方式:
@Configuration
public class Config {
//bean定義
}
任何一個標注了@Configuration的類都是一個JavaConfig配置類
2.Bean的定義層面
xml方式
<bean id="myBean" class="cn.sessiontech.service.xxxServerImpl">
...
</bean>
javaconfig方式
@Configuration
public class Config {
@Bean
public xxxServerImpl myBean() {
return new xxxServerImpl();
}
}
任何一個標注了@Bean的方法,其返回值將作為一個bean注冊至spring Ioc容器,方法名將默認成為此bean的id
3.Bean如果有依賴關系的層面
xml方式
<bean id="cp" class="cn.open.db.ConnectionProperty">
<constructor-arg index="0">
<ref bean="r" />
</constructor-arg>
</bean>
<bean id="r" class="org.springframework.core.io.ClassPathResource">
<constructor-arg index="0">
<value>/jdbc.properties</value>
</constructor-arg>
</bean>
javaconfig方式
@Configuration
public class Config {
@Bean
public ClassPathResource getResource() {
return new ClassPathResource("/jdbc.properties");
}
@Bean
public ConnectionProperty getConnectionProperty() {
return new ConnectionProperty(getResource());
}
}
4.xml文件導入另一個xml文件的層面
XML方式
<import resource="xxx.xml" />來導入配置文件
JavaConfig方式
@Import和@ImportResource
@Import(Xxx.class).只能是針對配置類。若還有部分是xml的,則用@ImportResource("xxx.xml")
其他
@PropertySource 注解,用於加載properties,可以聲明多個(java8或以上版本)
若想要多個,但低於java8版本,可以使用@PropertySources來
默認情況下的Bean是單例的。若要多實例的,則@Scope("prototype")注解修飾