使用SpringBoot的主要思想是习惯大于配置。使用Java配置代替XML配置。
在实际应用开发过程中也会存在不得不添加配置文件的情况,例如集成其他框架或者需要配置一些中间件等,在这种情况下,就需要引入自定义的xml配置文件。
@SpringBootApplication会自动扫描当前包以及子包中的bean
模拟创建一个不和启动类在同一个包中的bean,编写spring配置文件由容器负责实例化。
package other;
public class OtherBean {
public OtherBean(){
System.out.println("我是有外部xml实例化的");
}
}
编写spring配置文件
<?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-3.0.xsd">
<bean id="otherBean" class="other.OtherBean"></bean>
</beans>
在启动类上添加注解:
@ImportResource(locations= {“classpath:application-bean.xml”})
测试启动时,控制台会打印构造方法中输出的内容。
7.SpringBoot多数据源支持
实际项目中,可能不仅会面临单一数据源的状况,甚至还会遇到多数据源的状况。
使用DBCP、和Druid 数据源,连接MySql中不同的Database
创建2个Database
create database master; -- 主库 使用DBCP数据源
create database cluster; -- 从库 使用Druid数据源
添加依赖
<parent>
<groupId>
org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
application.properties
spring.datasource.master.url=jdbc:mysql://localhost:3306/master
spring.datasource.master.username=root
spring.datasource.master.password=root
spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.master.type=org.apache.commons.dbcp.BasicDataSource
spring.datasource.cluster.url=jdbc:mysql://localhost:3306/cluster
spring.datasource.cluster.username=root
spring.dat