Skip to content

Commit 5e4e645

Browse files
committed
@BeanFactoryAware 去注册对象 @
1 parent 94c9a27 commit 5e4e645

5 files changed

Lines changed: 120 additions & 95 deletions

File tree

src/main/java/cn/iwuliao/ds/core/Db.java

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
package cn.iwuliao.ds.core;
22

3-
import com.alibaba.druid.pool.DruidDataSource;
43
import lombok.Getter;
54
import lombok.Setter;
65
import lombok.ToString;
76

7+
import java.util.Map;
88
import java.util.Properties;
99

1010
@Setter
1111
@Getter
1212
@ToString
1313
public class Db {
1414

15-
// private DruidDataSource master;
16-
// private DruidDataSource slave;
17-
// private DruidDataSource slave1;
18-
//
1915
private Properties master;
20-
private Properties slave;
21-
private Properties slave1;
16+
17+
private Map<String, Properties> slaves;
2218

2319
private String mapperLocations;
2420
private String typeHandlersPackage;

src/main/java/cn/iwuliao/ds/core/DbConf1.java renamed to src/main/java/cn/iwuliao/ds/core/DbConf.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package cn.iwuliao.ds.core;
22

33
import lombok.*;
4+
import org.springframework.boot.context.properties.ConfigurationProperties;
5+
import org.springframework.context.annotation.Configuration;
46

57
import java.util.Map;
68
import java.util.Properties;
@@ -10,7 +12,9 @@
1012
@ToString
1113
@NoArgsConstructor
1214
@AllArgsConstructor
13-
public class DbConf1 {
15+
@Configuration
16+
@ConfigurationProperties(prefix = "druid2")
17+
public class DbConf {
1418

1519
private String poolType;
1620

src/main/java/cn/iwuliao/ds/core/DbContextHolder.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
public class DbContextHolder {
77

88
public enum DbType {
9-
MASTER, SLAVE
9+
MASTER, SLAVE, SLAVE1
1010
}
1111

1212
private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<>();

src/main/java/cn/iwuliao/ds/core/DsScannerConfigurer.java

Lines changed: 69 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,27 @@
1010
import org.springframework.beans.BeanMetadataAttribute;
1111
import org.springframework.beans.BeanUtils;
1212
import org.springframework.beans.BeansException;
13+
import org.springframework.beans.factory.BeanFactory;
14+
import org.springframework.beans.factory.BeanFactoryAware;
15+
import org.springframework.beans.factory.InitializingBean;
1316
import org.springframework.beans.factory.annotation.Autowired;
17+
import org.springframework.beans.factory.annotation.Value;
1418
import org.springframework.beans.factory.config.*;
1519
import org.springframework.beans.factory.parsing.DefaultsDefinition;
1620
import org.springframework.beans.factory.support.*;
21+
import org.springframework.boot.context.properties.ConfigurationProperties;
1722
import org.springframework.boot.jdbc.DataSourceBuilder;
1823
import org.springframework.boot.json.YamlJsonParser;
1924
import org.springframework.cglib.beans.BeanMap;
25+
import org.springframework.context.ApplicationContext;
26+
import org.springframework.context.ApplicationContextAware;
27+
import org.springframework.context.ApplicationEvent;
28+
import org.springframework.context.ApplicationListener;
2029
import org.springframework.context.annotation.Bean;
2130
import org.springframework.context.annotation.ComponentScan;
2231
import org.springframework.context.annotation.Configuration;
32+
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
33+
import org.springframework.core.Ordered;
2334
import org.springframework.core.env.ConfigurableEnvironment;
2435
import org.springframework.core.env.Environment;
2536
import org.springframework.core.env.MutablePropertySources;
@@ -34,65 +45,56 @@
3445
import org.yaml.snakeyaml.representer.Representer;
3546

3647
import javax.sql.DataSource;
48+
import java.sql.SQLException;
49+
import java.time.LocalDateTime;
3750
import java.util.*;
3851

3952
/**
4053
*
4154
*/
4255
@Component
43-
public class DsScannerConfigurer {
56+
public class DsScannerConfigurer implements BeanFactoryAware, Ordered, ApplicationContextAware {
4457

58+
private BeanFactory beanFactory;
4559

4660
private static final String PREFIX = "druid2.";
4761
private static final String DRUID_DS_PROPS_PREFIX = "druid.";
4862
public static final String TRANSACTIONMANAGER = "TransactionManager";
4963
private static final String MAPPERSCANNERCONFIGURER = "MapperScannerConfigurer";
5064
public static final String SQLSESSIONFACTORY = "SqlSessionFactory";
5165

52-
@Bean
53-
public BeanDefinitionRegistryPostProcessor factory(final StandardServletEnvironment environment) {
54-
55-
return new BeanDefinitionRegistryPostProcessor() {
56-
@Override
57-
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
58-
MutablePropertySources propertySources = environment.getPropertySources();
59-
Properties properties = new Properties();
60-
propertySources.forEach(x -> {
61-
Object source = x.getSource();
62-
if (source instanceof LinkedHashMap) {
63-
LinkedHashMap props = (LinkedHashMap) source;
64-
props.forEach((k, v) -> {
65-
String key = k.toString();
66-
boolean druid2 = key.startsWith(PREFIX);
67-
if (druid2) {
68-
properties.put(key, v);
69-
}
70-
});
71-
}
72-
});
73-
boolean empty = properties.isEmpty();
74-
if (!empty) {
75-
DbConf1 dbConf1 = getDsConfBean(properties);
76-
try {
77-
registryDs(dbConf1, registry);
78-
} catch (Exception e) {
79-
e.printStackTrace();
80-
}
81-
}
82-
}
8366

67+
@Autowired
68+
private DbConf dbConf;
8469

85-
@Override
86-
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
70+
@Override
71+
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
72+
this.beanFactory = beanFactory;
73+
}
74+
75+
76+
@Override
77+
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
78+
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
79+
try {
80+
registryDs(registry);
81+
} catch (ClassNotFoundException e) {
82+
e.printStackTrace();
83+
}
8784

88-
}
89-
};
9085
}
9186

92-
private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) throws Exception {
93-
String poolType = properties.getPoolType();
87+
@Override
88+
public int getOrder() {
89+
return -100;
90+
}
91+
92+
93+
private void registryDs(BeanDefinitionRegistry registry) throws ClassNotFoundException {
94+
String poolType = dbConf.getPoolType();
9495
if (Objects.nonNull(poolType)) {
95-
Map<String, Db> dbs = properties.getDbs();
96+
97+
Map<String, Db> dbs = dbConf.getDbs();
9698
Set<Map.Entry<String, Db>> entries = dbs.entrySet();
9799
for (Map.Entry<String, Db> entry : entries) {
98100
String dbName = entry.getKey();
@@ -101,18 +103,24 @@ private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) thr
101103
String mapperScannerPackage = value.getMapperScannerPackage();
102104
String typeHandlersPackage = value.getTypeHandlersPackage();
103105
Properties masterProperties = getDsProps(value.getMaster());
104-
Properties slaveProperties = getDsProps(value.getSlave());
105-
106+
Map<String, Properties> slaves = value.getSlaves();
107+
List<Properties> salves1 = new ArrayList<>();
108+
if (Objects.nonNull(slaves)) {
109+
slaves.entrySet().forEach(x -> salves1.add(getDsProps(slaves.get(x))));
110+
}
106111
DruidDataSource master = new DruidDataSource();
107112
master.setConnectProperties(masterProperties);
108-
master.init();
109-
110-
DruidDataSource slave = new DruidDataSource();
111-
slave.setConnectProperties(slaveProperties);
112-
slave.init();
113+
List<DruidDataSource> slaveDatasources = new ArrayList<>();
114+
if (!salves1.isEmpty()) {
115+
salves1.forEach(x -> {
116+
DruidDataSource ds = new DruidDataSource();
117+
ds.setConnectProperties(x);
118+
slaveDatasources.add(ds);
119+
});
120+
}
113121

114122
//获取动态数据源
115-
registryDynamicDs(master, slave, dbName, registry);
123+
registryDynamicDs(master, slaveDatasources, dbName, registry);
116124
//事物
117125
registryDynamicDsTrancationManager(dbName, registry);
118126

@@ -125,6 +133,7 @@ private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) thr
125133
}
126134
}
127135

136+
128137
private Properties getDsProps(Properties master) {
129138
Properties props = new Properties();
130139
Enumeration<?> enumeration = master.propertyNames();
@@ -171,11 +180,14 @@ private void registryDynamicDsTrancationManager(String dbName, BeanDefinitionReg
171180
registry.registerBeanDefinition(dbName + TRANSACTIONMANAGER, beanDefinition);
172181
}
173182

174-
private void registryDynamicDs(DruidDataSource master, DruidDataSource slave, String dbName, BeanDefinitionRegistry registry) {
183+
private void registryDynamicDs(DruidDataSource master, List<DruidDataSource> slaves, String dbName, BeanDefinitionRegistry registry) {
175184

176185
Map<Object, Object> targetDataResources = new HashMap<>();
177186
targetDataResources.put(DbContextHolder.DbType.MASTER, master);
178-
targetDataResources.put(DbContextHolder.DbType.SLAVE, slave);
187+
if (Objects.nonNull(slaves) && !slaves.isEmpty()) {
188+
targetDataResources.put(DbContextHolder.DbType.SLAVE, slaves.get(0));
189+
}
190+
179191

180192
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
181193
beanDefinition.setBeanClass(MasterSlaveRoutingDataSource.class);
@@ -186,7 +198,13 @@ private void registryDynamicDs(DruidDataSource master, DruidDataSource slave, St
186198
}
187199

188200

189-
private DbConf1 getDsConfBean(Properties properties) {
201+
/**
202+
* 目前无效代码了
203+
*
204+
* @param properties
205+
* @return
206+
*/
207+
private DbConf getDsConfBean(Properties properties) {
190208
PropertiesToYamlConverter converter = new PropertiesToYamlConverter();
191209

192210
StringBuilder sb = new StringBuilder();
@@ -207,25 +225,8 @@ private DbConf1 getDsConfBean(Properties properties) {
207225

208226
Map ymalMap = yaml.loadAs(docment, Map.class);
209227
String s = JsonUtil.toJsonStr(ymalMap);
210-
DbConf1 dbConf11 = JsonUtil.json2Bean(s, DbConf1.class);
228+
DbConf dbConf11 = JsonUtil.json2Bean(s, DbConf.class);
211229
return dbConf11;
212230
}
213-
214-
public static void main(String[] args) {
215-
Map ymalMap = new HashMap();
216-
ymalMap.put("poolType", "wwwww");
217-
DbConf1 dbConf1 = new DbConf1();
218-
BeanMap beanMap = BeanMap.create(dbConf1);
219-
beanMap.putAll(ymalMap);
220-
221-
String s = JsonUtil.toJsonStr(ymalMap);
222-
DbConf1 dbConf11 = JsonUtil.json2Bean(s, DbConf1.class);
223-
224-
225-
System.out.println(dbConf11);
226-
227-
}
228-
229-
230231
}
231232

src/main/resources/application.yml

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
11

2+
3+
datasource1:
4+
pool-type: com.alibaba.druid.pool.DruidDataSource
5+
ds:
6+
url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
7+
driverClassName: com.mysql.cj.jdbc.Driver
8+
username: root
9+
password: 123456
10+
initialSize: '1'
11+
minIdle: '1'
12+
maxActive: '20'
13+
testOnBorrow: 'true'
14+
215
druid2:
316
poolType: com.alibaba.druid.pool.DruidDataSource
417
dbs:
@@ -15,15 +28,25 @@ druid2:
1528
minIdle: '1'
1629
maxActive: '20'
1730
testOnBorrow: 'true'
18-
slave:
19-
url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
20-
driverClassName: com.mysql.cj.jdbc.Driver
21-
username: root
22-
password: 123456
23-
initialSize: '1'
24-
minIdle: '1'
25-
maxActive: '20'
26-
testOnBorrow: 'true'
31+
slaves:
32+
slave0:
33+
url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
34+
driverClassName: com.mysql.cj.jdbc.Driver
35+
username: root
36+
password: 123456
37+
initialSize: '1'
38+
minIdle: '1'
39+
maxActive: '20'
40+
testOnBorrow: 'true'
41+
slave1:
42+
url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
43+
driverClassName: com.mysql.cj.jdbc.Driver
44+
username: root
45+
password: 123456
46+
initialSize: '1'
47+
minIdle: '1'
48+
maxActive: '20'
49+
testOnBorrow: 'true'
2750
dbb:
2851
mapperLocations: classpath:mybatis/dbb/*.xml
2952
typeHandlersPackage:
@@ -37,15 +60,16 @@ druid2:
3760
minIdle: '1'
3861
maxActive: '20'
3962
testOnBorrow: 'true'
40-
slave:
41-
url: jdbc:mysql://127.0.0.1:3306/dbb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
42-
driverClassName: com.mysql.cj.jdbc.Driver
43-
username: root
44-
password: 123456
45-
initialSize: '1'
46-
minIdle: '1'
47-
maxActive: '20'
48-
testOnBorrow: 'true'
63+
slaves:
64+
slave0:
65+
url: jdbc:mysql://127.0.0.1:3306/dbb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong
66+
driverClassName: com.mysql.cj.jdbc.Driver
67+
username: root
68+
password: 123456
69+
initialSize: '1'
70+
minIdle: '1'
71+
maxActive: '20'
72+
testOnBorrow: 'true'
4973

5074
logging:
5175
level:

0 commit comments

Comments
 (0)