自学内容网 自学内容网

使用三方框架,手动注入到spring中

背景:我们公司的项目需要重构,原本的框架是公司之前的员工自主研发的,但是后来又要重构成主流框架,但是由于有些功能还需要用到原本的框架的,我就把他引入了,

话不多说,直接上代码

@EnableCaching // 启用缓存
@EnableScheduling // 启动定时任务
@SpringBootApplication // springboot本尊
@EnableTransactionManagement // 启动注解事务管理
@EnableFeignClients// 启用Feign实现RPC调用
@ComponentScan(basePackages = {"com.pj", "net.atomarrow", "net.atomarrow.services"}) // 确保包含所有需要扫描的包
@Slf4j
public class PblBaseApplication  {

public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(PblBaseApplication.class);
//打印服务信息
SpCloudUtil.printCurrentServiceInfo();
//手动注入,让spring管理
initServices(context);
}

/**
 * 获取 JdbcService 和 Service 实例,并通过反射将 JdbcService 注入到 Service 中
 * 只能这么用,因为jdbcService是atomarrow的,无法用注解,让spring管理
 * @param context
 */
private static void initServices(ApplicationContext context) {
// 获取 JdbcService 和 Service 实例
JdbcService jdbcService = context.getBean(JdbcService.class);
Service service =  context.getBean("institutionService",Service.class);

// 手动注入 JdbcService
try {
Field field = Service.class.getDeclaredField("service");
field.setAccessible(true);
field.set(service, jdbcService);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Failed to inject JdbcService into Service", e);
}
}


/**
 * 加上这段代码的目的是为了在 Spring Boot 启动时,在启动atomarrow框架,
 * atomarrow框架是为了创建校区的时候生表用的,为什么用这个,是因为项目重构之前用的这个框架
 * @return
 */
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
AppStarter appStarter = new AppStarter();
appStarter.contextInitialized(servletContextEvent);
}
};
}

}

原文地址:https://blog.csdn.net/yuzheh521/article/details/142881067

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!