SpringBoot多重屬性檔案配置方案筆記
阿新 • • 發佈:2022-04-16
SpringBoot多重屬性檔案配置方案筆記
-
需要重寫PropertyPlaceholderConfigurer
-
同時要忽略DataSourceAutoConfiguration
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) //@EnableTransactionManagement 2. 嘗試xml配置事務 @ImportResource(locations = {"classpath:spring-tx.xml"}) public class DemoTransactionApplication { public static void main(String[] args) { SpringApplication.run(DemoTransactionApplication.class, args); } }
-
由於忽略了DataSourceAutoConfiguration,所以要配置datasource的Bean,和sqlSessionFactory 的Bean
@Configuration @MapperScan(basePackages = {MyBatisConfig.MAPPER_PACKAGE}, sqlSessionFactoryRef = MyBatisConfig.SESSIONFACTORY_NAME) public class MyBatisConfig { /**SqlSessionFactory名稱.*/ public final static String SESSIONFACTORY_NAME = "sqlSessionFactory"; /**mapper包路徑,必須與其他SqlSessionFactory-mapper路徑區分.*/ public final static String MAPPER_PACKAGE = "com.grady.demotransaction.mapper"; /**mapper.xml檔案路徑,必須與其他SqlSessionFactory-mapper路徑區分.*/ public final static String MAPPER_XML_PATH = "classpath:mapper/*.xml"; @Value("${spring.datasource.url}") private String datasourceUrl; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.username}") private String userName; @Value("${spring.datasource.password}") private String password; @Bean(name = "dataSource") public DataSource dataSource() { //建議封裝成單獨的類 DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(datasourceUrl); dataSource.setDriverClassName(driverClassName); dataSource.setUsername(userName); dataSource.setPassword(password); return dataSource; } //預設Bean首字母小寫,簡化配置 //將SqlSessionFactory作為Bean注入到Spring容器中,成為配置一部分。 @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_XML_PATH)); return sqlSessionFactoryBean.getObject(); } }
-
這樣就可以將本來都寫在application.properties中的配置拆成多個了(這裡是兩個)
application.properties
spring.main.allow-bean-definition-overriding=true server.port=8080 mybatis.config-location=classpath:config/mybatis-config.xml mybatis.mapper-locations=classpath:mapper/*.xml
datasource.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost/sampledb spring.datasource.username=root spring.datasource.password=123456
-