本文的目标是通过springboot提供的支持,使用户在springboot项目中导入我们的依赖就可以自动注入bean实现功能,本次以自定义的DbHelper为例,一个简化jdbc操作的简单程序
1.主配置类
首先使用@Configuration定义为配置类
然后使用@EnableConfigurationProperties({DbProperties.class}),加载配置文件中的属性,这个类后面会给出
然后加上条件注解,表面只有存在DbProperties这个类时才加载这个
@Configuration
@EnableConfigurationProperties({DbProperties.class})
@ConditionalOnClass({ DbProperties.class})
public class SystemInfoAutoConfiguration {
/**
* 按条件加载Dbhelper,如果没用数据库驱动则不加载
*/
@Bean
@ConditionalOnClass(name="com.mysql.cj.jdbc.Driver")
public DBHelper dbHelper() {
System.out.println("加载了DBHelper");
return new DBHelper();
}
}
2.读取配置文件的属性
这里使用的注解的功能时获取配置文件为yc.db的属性
比如用户可以设置url为yc.db.url,以此类推
@ConfigurationProperties(prefix = "yc.db")
public class DbProperties{
String url;
String uname;
String pwd;
String driver;
3.DbHelper实现
这里首先就是加载属性,获取数据库连接,并且实现了一个查询方法,传入数据实体类,sql语句和具体参数进行查询
public class DBHelper {
@Autowired
private DbProperties dbProperties;
//获取一个Connection
public Connection getConnection( ) throws SQLException {
System.out.println(dbProperties);
try{
Class.forName(dbProperties.getDriver());
}catch (ClassNotFoundException e){
throw new RuntimeException(e);
}
return DriverManager.getConnection( dbProperties.getUrl(), dbProperties.getUname(), dbProperties.getPwd());
}
public <T> List<T> select(Class<T> c, String sql, Object... params) throws InstantiationException, IllegalAccessException, InvocationTargetException {
List<T> result = new ArrayList<>();
List<Map<String, Object>> list = this.select(sql, params);
for (Map<String, Object> map : list) {
T t = null; // 使用更通用的方式创建实例
try {
t = c.getDeclaredConstructor().newInstance();
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// 处理属性名
String methodName = "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);
try {
Method setMethod = c.getMethod(methodName, value.getClass());
setMethod.invoke(t, value); // 使用反射动态调用 set 方法
} catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
// 处理异常情况
e.printStackTrace(); // 可以根据具体情况选择如何处理异常
}
}
result.add(t);
}
return result;
}
}
4.利用spi机制加载主配置类
在这个目录下创建指定的文件
文件名为org.springframework.boot.autoconfigure.AutoConfiguration.imports
里面写上要加载的主配置类的位置比如
com.yc.SystemInfoAutoConfiguration
对于springboot的源码中也是这么实现加载的
5.打包部署
记得导入依赖先,这里主要是自动配置的依赖和springboot的父依赖,并且记住打包后的名字
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<scope>compile</scope>
</dependency>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yc</groupId>
<artifactId>dbhelper_start</artifactId>
<version>1.0.1</version>
<packaging>jar</packaging>
在maven工具的生命周期中选择install,等待打包完成
5.测试
在springboot项目中导入依赖,这里是此项目的依赖以及mysql的连接依赖
<dependency>
<groupId>com.yc</groupId>
<artifactId>dbhelper_start</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
写好测试的类,这里使用controller层中写一个访问的方法
@RestController
public class MyDb {
@Autowired
private DBHelper db;
@RequestMapping("/")
public String index() {
String sql = "select * from user";
List<User> users;
try {
users = db.select(User.class, sql);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
return "Hello World!" + users;
}
}
配置文件中要加入相关配置,端口改成80可以不用输入端口号,因为浏览器默认端口为80,所以
只要启动后在浏览器中输入localhost就可以看到结果
server:
port: 80
yc:
db:
url: jdbc:mysql://localhost:3306/myuser
uname: yourname
pwd: yourpwd
driver: com.mysql.cj.jdbc.Driver
结果,查询数据成功