optimize spring boot starter

This commit is contained in:
开源海哥 2023-04-12 15:28:11 +08:00
parent 5697cdebf4
commit aa26e5ae83
7 changed files with 104 additions and 77 deletions

View File

@ -15,6 +15,7 @@
*/
package com.mybatisflex.core.datasource;
import com.mybatisflex.core.exception.FlexExceptions;
import com.mybatisflex.core.util.ConvertUtil;
import com.mybatisflex.core.util.StringUtil;
import org.apache.ibatis.reflection.Reflector;
@ -57,8 +58,13 @@ public class DataSourceBuilder {
dataSourceClassName = detectDataSourceClass();
}
if (StringUtil.isBlank(dataSourceClassName)) {
throw new IllegalArgumentException("Cannot find the dataSource type: " + type);
if (StringUtil.isBlank(type)) {
throw FlexExceptions.wrap("The dataSource type can not be null or blank.");
} else {
throw FlexExceptions.wrap("Cannot find the dataSource type: " + type);
}
}
try {

View File

@ -18,33 +18,42 @@ package com.mybatisflex.spring.boot;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
import java.util.Iterator;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(ConditionalOnPropertyEmpty.OnPropertyNotEmptyCondition.class)
public @interface ConditionalOnPropertyEmpty {
@Conditional(ConditionalOnMybatisFlexDatasource.OnMybatisFlexDataSourceCondition.class)
public @interface ConditionalOnMybatisFlexDatasource {
String value();
class OnPropertyNotEmptyCondition implements Condition {
class OnMybatisFlexDataSourceCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attrs = metadata.getAnnotationAttributes(ConditionalOnPropertyEmpty.class.getName());
if (attrs == null) {
return false;
Environment env = context.getEnvironment();
if (env instanceof AbstractEnvironment) {
MutablePropertySources propertySources = ((AbstractEnvironment) env).getPropertySources();
Iterator<PropertySource<?>> it = propertySources.stream().iterator();
while (it.hasNext()) {
PropertySource ps = it.next();
if (ps instanceof MapPropertySource) {
for (String propertyName : ((MapPropertySource) ps).getSource().keySet()) {
if (propertyName.startsWith("mybatis-flex.datasource.")) {
return true;
}
}
}
}
}
String propertyName = (String) attrs.get("value");
String val = context.getEnvironment().getProperty(propertyName);
return val == null || val.trim().length() == 0;
return false;
}
}
}

View File

@ -35,7 +35,7 @@ import java.util.Map;
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnPropertyEmpty("spring.datasource.url")
@ConditionalOnMybatisFlexDatasource()
@EnableConfigurationProperties(MybatisFlexProperties.class)
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
public class MultiDataSourceAutoConfiguration {

View File

@ -45,6 +45,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
@ -78,7 +79,7 @@ import java.util.stream.Stream;
* 2修改 SqlSessionFactory FlexSqlSessionFactoryBean
* 3修改 Configuration FlexConfiguration
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisFlexProperties.class)

View File

@ -15,12 +15,13 @@
*/
package com.mybatisflex.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@MapperScan("com.mybatisflex.test.mapper")
@MapperScan("com.mybatisflex.test.mapper")
public class SampleApplication implements CommandLineRunner {

View File

@ -1,60 +1,60 @@
///**
// * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
// * <p>
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// * <p>
// * http://www.apache.org/licenses/LICENSE-2.0
// * <p>
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.mybatisflex.test.controller;
//
//import com.mybatisflex.core.paginate.Page;
//import com.mybatisflex.core.query.QueryWrapper;
//import com.mybatisflex.test.mapper.AccountMapper;
//import com.mybatisflex.test.model.Account;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.Arrays;
//import java.util.List;
//import java.util.stream.Collectors;
//
//@RestController
//public class AccountController {
//
// @Autowired
// AccountMapper accountMapper;
//
//
// @PostMapping("/account/add")
// String add(@RequestBody Account account){
// accountMapper.insert(account);
// return "add ok!";
// }
//
//
// @GetMapping("/account/{id}")
// Account selectOne(@PathVariable("id") Long id) {
// return accountMapper.selectOneById(id);
// }
//
//
// @GetMapping("/selectListByIds/{id}")
// List<Account> selectListByIds(@PathVariable("id") String id) {
// List<Long> ids = Arrays.stream(id.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
// return accountMapper.selectListByIds(ids);
// }
//
//
// @GetMapping("/paginate")
// Page<Account> paginate(@RequestParam(defaultValue = "1") int pageNumber, @RequestParam(defaultValue = "10") int pageSize) {
// return accountMapper.paginate(pageNumber,pageSize, QueryWrapper.create());
// }
//}
/**
* Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mybatisflex.test.controller;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.test.mapper.AccountMapper;
import com.mybatisflex.test.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class AccountController {
@Autowired
AccountMapper accountMapper;
@PostMapping("/account/add")
String add(@RequestBody Account account){
accountMapper.insert(account);
return "add ok!";
}
@GetMapping("/account/{id}")
Account selectOne(@PathVariable("id") Long id) {
return accountMapper.selectOneById(id);
}
@GetMapping("/selectListByIds/{id}")
List<Account> selectListByIds(@PathVariable("id") String id) {
List<Long> ids = Arrays.stream(id.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
return accountMapper.selectListByIds(ids);
}
@GetMapping("/paginate")
Page<Account> paginate(@RequestParam(defaultValue = "1") int pageNumber, @RequestParam(defaultValue = "10") int pageSize) {
return accountMapper.paginate(pageNumber,pageSize, QueryWrapper.create());
}
}

View File

@ -11,4 +11,14 @@ spring:
sql:
init:
schema-locations: classpath:schema.sql
data-locations: classpath:data.sql
data-locations: classpath:data.sql
#mybatis-flex:
# datasource:
# ds1:
# url: jdbc:mysql://127.0.0.1:3306/db
# username: root
# password: 123456
# ds2:
# url: jdbc:mysql://127.0.0.1:3306/db2
# username: root
# password: 123456