1. 背景
在 Spring Boot 项目中,我们通常使用 @Autowired
或 @Resource
进行 Bean 的依赖注入。然而,在非 Spring Boot 项目中,通常需要手动管理 Spring 容器,因此默认的自动注入机制可能无法直接使用。那么,我们如何在非 Spring Boot 项目中实现类似 @Autowired
或 @Resource
的自动注入呢?毕竟使用 @Autowired
或 @Resource
的写法相对于 private Foo foo = ...;
还是非常香的。虽然如此,但是目前我仍然觉得Springboot太重,只适合企业级应用程序开发,对于高并发的SaaS项目绝对不适合。
最后回到问题的源点:对于非Springboot项目该怎么搞呢?想想,还是自己动手撸吧!本文将介绍如何使用自定义注解在非 Spring Boot 项目中实现 Bean 自动注入及管理。
2. 实现思路
2.1 手动管理 Spring 容器
由于项目不是Spring Boot项目,我们无法使用 @ComponentScan
或 @Configuration
等Spring Boot特性。因此,我们需要手动管理Spring容器,可以手动创建一个AnnotationConfigApplicationContext
作为Spring上下文。如果你是多项目统一部署和启动则需要注意公共的:AnnotationConfigApplicationContext
其refresh()
方法只允许调用一次;
2.2 使用BeanPostProcessor 在 Bean 初始化前后进行介入
BeanPostProcessor 是 Spring 的一个扩展接口,允许在 Spring 容器实例化 Bean 之后,初始化 Bean 之前和之后,对 Bean 进行额外的处理或修改。在 非 Spring Boot 项目中,它仍然可以使用,只是需要手动注册到 ApplicationContext 而已。
-
BeanPostProcessor 的作用一般为:
1、在 Bean 初始化前/后 进行额外处理(例如,自动注入)。对应方法为:postProcessBeforeInitialization()、postProcessAfterInitialization()。
2、动态代理(AOP、事务管理、懒加载)。
3、修改 Bean 属性(例如,自动填充某些字段)。
4、增强 Bean 功能(如 @Autowired、@Resource 等依赖注入的底层实现)。
5、跟踪 Bean 生命周期(可用于调试和日志记录)。 -
需要添加的Maven依赖为:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
3. 主要实现代码
3.1 自定义注解@PluginResource
首先,我们定义一个注解@PluginResource,用于标识需要自动注入的字段。
package cn.bossfriday.common.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* PluginResource
*
* @author chenx
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PluginResource {
/**
* type
*
* @return
*/
Class<?> type() default Object.class;
}
3.2 BeanPostProcessor扩展实现
package cn.bossfriday.common.plugin;
import cn.bossfriday.common.exception.ServiceRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.Field;
/**
* PluginResourcePostProcessor
* <p>
* Spring 容器在实例化一个 Bean 时,会在初始化前后自动调用 BeanPostProcessor 来支持对Bean的额外的处理或修改;
* 这里的目的是实现 @PluginResource 的自动注入;
*
* @author chenx
*/
@Slf4j
public class PluginResourcePostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> clazz = bean.getClass();
for (Field field : clazz.getDeclaredFields()) {
PluginResource annotation = field.getAnnotation(PluginResource.class);
if (annotation != null) {
this.injectBean(bean, field, annotation);
log.info(" - Bean {} ", clazz.getName());
}
}
return bean;
}
/**
* injectBean
*/
private void injectBean(Object bean, Field field, PluginResource annotation) {
try {
Class<?> type = annotation.type();
if (type == Object.class) {
type = field.getType();
}
Object dependency = PluginSpringContext.getBean(type);
if (dependency != null) {
field.setAccessible(true);
field.set(bean, dependency);
} else {
throw new ServiceRuntimeException("No bean found for type: " + type.getName());
}
} catch (Exception ex) {
throw new ServiceRuntimeException("Failed to inject PluginResource into " + bean.getClass().getName());
}
}
}
3.3 手动管理 Spring 容器实现
package cn.bossfriday.common.plugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Objects;
/**
* PlugSpringContext
*
* @author chenx
*/
@Slf4j
public class PluginSpringContext {
private static AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
private PluginSpringContext() {
// do nothing
}
static {
context.setClassLoader(Thread.currentThread().getContextClassLoader());
}
/**
* initialize
*
* @param basePackages
*/
public static void initialize(String... basePackages) {
// 手动注册 PluginResourcePostProcessor
context.getBeanFactory().addBeanPostProcessor(new PluginResourcePostProcessor());
// scan & refresh
context.scan(basePackages);
context.refresh();
log.info("PluginSpringContext.refresh() done");
}
/**
* getBean
*/
public static <T> T getBean(Class<T> clazz) {
if (Objects.isNull(clazz)) {
return null;
}
return context.getBean(clazz);
}
}
3.4 使用示例
package cn.bossfriday.im.common.cache;
import cn.bossfriday.common.plugin.PluginResource;
import cn.bossfriday.im.common.db.AppInfoDao;
import cn.bossfriday.im.common.db.entity.AppInfo;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static cn.bossfriday.im.common.constant.ImConstant.*;
/**
* AppInfoCacheService
*
* @author chenx
*/
@Slf4j
@Service
public class AppInfoCacheService {
@PluginResource
private AppInfoDao appInfoDao;
private Cache<Long, Optional<AppInfo>> appInfoCache = Caffeine.newBuilder()
.initialCapacity(CACHE_DEFAULT_INITIAL_CAPACITY)
.maximumSize(CACHE_DEFAULT_MAXIMUM_SIZE)
.expireAfterWrite(CACHE_EXPIRE_TWO_HOURS, TimeUnit.SECONDS)
.build();
/**
* getAppInfo
*
* @param appId
* @return
*/
public AppInfo getAppInfo(Long appId) {
Optional<AppInfo> cached = this.appInfoCache.getIfPresent(appId);
if (Objects.nonNull(cached)) {
return cached.orElse(null);
}
return this.appInfoCache.get(appId, key -> Optional.ofNullable(this.getAppInfoFromDb(key))).orElse(null);
}
/**
* getAppInfoFromDb
*/
private AppInfo getAppInfoFromDb(Long appId) {
return this.appInfoDao.getById(appId);
}
}
需要重点补充说明的是:服务启动时需要显示调用PluginSpringContext.initialize(...)
方法;例如下面是我的一个子服务的启动类,其中@PluginApplication
是不是看上去跟Springboot的@SpringBootApplication
也很像呢?但是实际上里面所有的子服务根本不是Springboot项目;
package cn.bossfriday.im.api;
import cn.bossfriday.common.plugin.PluginApplication;
import cn.bossfriday.common.plugin.PluginSpringContext;
import cn.bossfriday.im.api.http.HttpApiServer;
import cn.bossfriday.im.common.PluginBootstrap;
import cn.bossfriday.im.common.conf.ConfigurationAllLoader;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
import static cn.bossfriday.im.common.constant.ImConstant.BASE_PACKAGE_NAME;
import static cn.bossfriday.im.common.constant.ImConstant.SERVICE_NAME_API;
/**
* ApiBootstrap
* <p>
* IM接口服务:对外提供IM系统相关HTTP接口
*
* @author chenx
*/
@Slf4j
@PluginApplication(name = SERVICE_NAME_API)
public class ApiBootstrap extends PluginBootstrap {
private HttpApiServer httpApiServer;
@Override
protected void start() {
try {
int port = ConfigurationAllLoader.getInstance().getImApiConfig().getHttpPort();
this.httpApiServer = new HttpApiServer(port);
this.httpApiServer.start();
} catch (InterruptedException ex) {
log.error("ApplicationBootstrap.start() Interrupted!", ex);
Thread.currentThread().interrupt();
} catch (Exception ex) {
log.error("ApplicationBootstrap.start() error!", ex);
}
}
@Override
protected void stop() {
try {
if (Objects.nonNull(this.httpApiServer)) {
this.httpApiServer.stop();
}
} catch (InterruptedException ex) {
log.error("ApplicationBootstrap.stop() Interrupted!", ex);
Thread.currentThread().interrupt();
} catch (Exception ex) {
log.error("ApplicationBootstrap.stop() error!", ex);
}
}
/**
* 本地测试启动入口
*/
public static void main(String[] args) {
PluginSpringContext.initialize(BASE_PACKAGE_NAME);
PluginBootstrap plugin = new ApiBootstrap();
plugin.startup(ConfigurationAllLoader.getInstance().getSystemConfig());
}
}
关于手撸IM专栏
- 【手撸IM】专题初衷为实现一个分布式、高性能、支持多租户的 IM 云原型,主要目的为开源学习交流。
- 源码地址:https://gitee.com/bossfriday/bossfriday-nubybear
【手撸IM】专栏导读
1.《【手撸IM】消息ID设计与实现》https://blog.csdn.net/camelials/article/details/136558285
2.《【手撸IM】通讯协议设计与实现》https://blog.csdn.net/camelials/article/details/136879608
备注:
1、由于国内访问github有一定问题,因此个人git迁移至gitee。
2、不管是没时间也好,自己懒也好,手撸IM的实现目前还是进展缓慢,不过还是认为将来可以拿出一个能自圆其说的高效 IM 脚手架项目的。当前主要改动是:经过再三思考还是决定使用MySql数据库了(数据库初始化脚本为:DB_Script_MySQL.sql)、修改了服务的启动方式,支持了所有子服务的单进程统一启动;后续的计划是先实现建连相关的实现。看上去简单,但是要做的基础工作还是很多,例如:实现导航、实现getToken的ServerAPI,同时为了后续业务开发的方便和需要,还要在原有Acotor RPC的基础上进行相关封装,例如:SSRequest(服务端-服务端 请求),SCRequest(服务端 - 客户端 请求)。当前已经实现了自定义注解@HttpApiRoute
的相关功能,有兴趣的同学可以去看下用Netty如何优雅的去组织请求和处理,毕竟Springboot的@RestController
用起来太方便了;我这里的实现主要是通过扩展ApiRequestType枚举来进行的,支持URL Path参数,通过Http方法+URL进行find。通过查看下面的代码,细心的朋友可能会提出一个质疑:find方法实际上是一个遍历查找,如果ApiRequestType.getByMethod(httpMethod)返回的list条目较多时,效率可能不好。由于要支持URL Path参数,因此无法通过哈希Map去处理,对于这种问题的优化手法一般是:使用 Trie(前缀树)来提高匹配速度。构建 Trie 结构后,查找 URL 不需要遍历 List,时间复杂度降低为 O(m)(m 为 URL 片段数)。考虑到目前Server API的接口数不会太多,因此这里只是简单提一下可用的优化方案,关于排序啊、查找啊里面的套路实在是叨叨叨叨的这里就不再往远的去扯蛋了。
@Slf4j
@HttpApiRoute(apiRouteKey = API_ROUTE_KEY_USER_GET_TOKEN)
public class GetTokenProcessor implements IHttpProcessor {
@Override
public void process(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {
log.info("GetTokenProcessor...");
}
}
public enum ApiRequestType {
/**
* client api
*/
CLIENT_NAV(API_ROUTE_KEY_CLIENT_NAV, HttpMethod.POST.name(), new UrlParser(String.format("/api/{%s}/client/nav", HTTP_URL_ARGS_API_VERSION))),
/**
* user api
*/
USER_GET_TOKEN(API_ROUTE_KEY_USER_GET_TOKEN, HttpMethod.POST.name(), new UrlParser(String.format("/api/{%s}/user/getToken", HTTP_URL_ARGS_API_VERSION))),
;
@Getter
private String apiRouteKey;
@Getter
private String httpMethod;
@Getter
private UrlParser urlParser;
ApiRequestType(String apiRouteKey, String httpMethod, UrlParser urlParser) {
this.apiRouteKey = apiRouteKey;
this.httpMethod = httpMethod;
this.urlParser = urlParser;
}
...
/**
* find
*
* @param httpMethod
* @param uri
* @return
*/
public static ApiRequestType find(String httpMethod, URI uri) {
List<ApiRequestType> list = ApiRequestType.getByMethod(httpMethod);
if (CollectionUtils.isEmpty(list)) {
return null;
}
for (ApiRequestType entry : list) {
if (entry.getUrlParser().isMatch(uri)) {
return entry;
}
}
return null;
}
}