SpringBoot引入外部xml配置文件&SpringBoot多数据源支持

使用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
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值