整合Spring(一) —— 让一个普通Maven项目用上Spring容器
admin
2024-05-11 02:26:07
0

Springboot大行其道的当下,很少有人单独自己整合Spring进行开发了,但是发现Spring提供的容器配合注解开发是真的非常方便。

有些非web项目使用Springboot开发难免有些不伦不类,为了能够既享受Spring带来的方便,又不让非web项目开发起来不这么不伦不类,我做了一系列的尝试,将Spring生态中的组件逐一自己做了整合。

网上很多整合案例,但是不少是需要xml的,这个整合系列尽可能的抛弃了xml方式的整合,而采用注解方式整合。

今天是这个系列的第一篇,将Spring引入一个普普通通的maven项目。

配置文件

导入Spring所有依赖文件

885.3.6

org.springframeworkspring-context${spring.version}org.springframeworkspring-core${spring.version}org.springframeworkspring-aop${spring.version}org.springframeworkspring-beans${spring.version}org.springframeworkspring-expression${spring.version}

打包插件

org.apache.maven.pluginsmaven-assembly-plugin3.0.0it.aspirin.HelloApplicationjar-with-dependenciesmake-assemblypackagesingle

项目结构

项目结构如下

主要创建了启动类HelloApplication.java,几个测试依赖注入的类HelloController.java, ImageService.java,ClickhouseImageServiceImpl.java,MysqlImageServiceImpl.java,ImageContext.java。下面会讲到。

├── pom.xml
└── src├── main│   ├── java│   │   └── it│   │       └── aspirin│   │           ├── HelloApplication.java│   │           ├── controller│   │           │   └── HelloController.java│   │           ├── mapper│   │           │   └── ImageMapper.java│   │           └── service│   │               ├── ImageService.java│   │               └── impl│   │                   ├── ClickhouseImageServiceImpl.java│   │                   ├── ImageContext.java│   │                   └── MysqlImageServiceImpl.java│   └── resources│       ├── application.properties└── test└── java

创建类

创建类添加注解

@Controller
public class HelloController {@Value("${jdbc.driver}")private String driver;public String sayHello(String name) {return driver + " hello " + name;}
}
@Service
public class ClickhouseImageServiceImpl implements ImageService {@Overridepublic String databaseType() {return "ck";}@Overridepublic String insert() {return "ck insert";}
}
@Service
public class MysqlImageServiceImpl implements ImageService {@ResourceImageService imageService;@Overridepublic String databaseType() {return "mysql";}@Overridepublic String insert() {return "mysql insert";}
}
@Service
public class ImageContext implements ApplicationContextAware {private final Map map = new ConcurrentHashMap<>();public String insert(String databaseType) {final ImageService imageService = Optional.ofNullable(map.get(databaseType)).orElseThrow(() -> new IllegalArgumentException("invalid database type:" + databaseType));return imageService.insert();}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {final Map tempMap = applicationContext.getBeansOfType(ImageService.class);tempMap.values().forEach(service -> map.put(service.databaseType(), service));}
}

启动类

启动类跟Springboot一样,主要添加包扫描注解ComponentScan,用法一样。

然后通过AnnotationConfigApplicationContext类获取创建的容器。比如下面获取了HelloController类的实例,这个类并没有通过new的方式实例化。

@ComponentScan("it.aspirin")
public class HelloApplication {public static void main(String[] args) {final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloApplication.class);final HelloController bean = context.getBean(HelloController.class);final String info = bean.sayHello("aspirin");LOGGER.info("info = {}", info);final ImageContext imageContext = context.getBean(ImageContext.class);LOGGER.info("imageContext.insert(\"mysql\") = " + imageContext.insert("mysql"));}
}

总结

单纯集成Spring相对比较简单。只需要导入依赖,添加ComponentScan扫描类即可。

然后通过AnnotationConfigApplicationContext对象获取到需要的对象。

这样的好处是创建单例对象变得非常容易,对象实例不再需要手动管理,而是交给Spring统一进行管理。

日常工作操作数据库必不可少,因此下期文章讲解无xml配置纯注解方式spring集成mybatis。

相关内容

热门资讯

【看表情包学Linux】进程地...   🤣 爆笑教程 👉 《看表情包学Linux》👈 猛...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
编译原理陈火旺版第三章课后题答... 下面答案仅供参考! 1.编写一个对于 Pascal 源程序的预处理程序。该程序的作用是...
MacBookPro M2芯片... MacBookPro M2芯片下如何搭建React-Native环境目录软件下载环境配置 目录 写在...
Android studio ... 解决 Android studio 出现“The emulator process for AVD ...
pyflink学习笔记(六):... 在pyflink学习笔记(一)中简单介绍了table-sql的窗口函数,下面简单介绍下...
创建deployment 创建deployment服务编排-DeploymentDeployment工作负载均衡器介绍Depl...
gma 1.1.4 (2023... 新增   1、地图工具    a. 增加【GetWorldDEMDataSet】。提供了一套 GEO...
AI专业教您保姆级在暗影精灵8... 目录 一、Stable Diffusion介绍    二、Stable Diffusion环境搭建 ...
vue笔记 第一个Vue应用 Document{{content}}{{...
Unity自带类 --- Ti... 1.在Unity中,自己写的类(脚本)的名字不能与Unit...
托福口语21天——day5 发... 目录 一、连读纠音 二、语料输入+造句输出 三、真题 一、连读纠音 英语中的连读方式有好几种...
五、排序与分页 一、排序 1、语法 ORDER BY 字段 ASC | DESC ASC(ascen...
Linux系统中如何安装软件 文章目录一、rpm包安装方式步骤:二、deb包安装方式步骤:三、tar....
开荒手册4——Related ... 0 写在前面 最早读文献的时候,每每看到related work部分都会选择性的忽略&...
实验01:吃鸡蛋问题 1.实验目的: 通过实验理解算法的概念、算法的表示、算法的时间复杂度和空间复杂度分析&...
8个免费图片/照片压缩工具帮您... 继续查看一些最好的图像压缩工具,以提升用户体验和存储空间以及网站使用支持。 无数图像压...
Spring Cloud Al... 前言 本文小新为大家带来 Sentinel控制台规则配置 相关知识,具体内容包括流控...
多项目同时进行,如何做好进度管... 多项目同时进行,如何做好进度管理? 大多数时候,面对项目进...
ATTCK红队评估实战靶场(二... 前言 第二个靶机来喽,地址:vulunstack 环境配置 大喊一声我...