因项目使用 Guice + Jersey + Jetty 框架,所有进行了学习,下面是学习笔记。

目录

一、Guice

1. 依赖注入方式: @Inject

2. 依赖绑定(依赖注册): bind()

3. 作用域

4. 基本使用

二、Jersey

使用内置容器为例(使用Jetty发布Jersey服务)

三、Jetty

四、Guice + Jersey + Jetty Demo


一、Guice

Guice 是谷歌推出的一个轻量级 依赖注入 框架。官网地址:GitHub - google/guice: Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 8 and above, brought to you by Google.

1. 依赖注入方式: @Inject

① 构造注入

public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic OrderServiceImpl(ItemService itemService, PriceService priceService) {this.itemService = itemService;this.priceService = priceService;}
}

② 一般注入

public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic void init(ItemService itemService, PriceService priceService) {this.itemService = itemService;this.priceService = priceService;}
}
public class OrderServiceImpl implements OrderService {private ItemService itemService;private PriceService priceService;@Injectpublic void setItemService(ItemService itemService) {this.itemService = itemService;}@Injectpublic void setPriceService(PriceService priceService) {this.priceService = priceService;}
}

2. 依赖绑定(依赖注册): bind()

Guice 提供依赖配置类:继承 AbstractModule,实现 configure 或者使用 @Provides 方法,完成依赖绑定。

Binder 语义:
基本配置:binder.bind(serviceClass).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
无base类、接口配置:binder.bind(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);
service实例配置:binder.bind(serviceClass).toInstance(servieInstance).in(Scopes.[SINGLETON | NO_SCOPE]);
多个实例按名注入:binder.bind(serviceClass).annotatedWith(Names.named(“name”)).to(implClass).in(Scopes.[SINGLETON | NO_SCOPE]);

① 基本绑定

public class BillingModule extends AbstractModule {@Override protected void configure() {bind(TransactionLog.class).to(DatabaseTransactionLog.class);}
}

② @Named 注解绑定(多实现绑定同一个接口)

// 1.注入的地方添加 @Named 注解
@Inject
public RealBillingService(@Named("Checkout") CreditCardProcessor processorg, TransactionLog transactionLog) {// ......
}// 2.在绑定中添加 annotatedWith 方法指定 @Named 中指定的名称
bind(TransactionLog.class).to(TransactionLogImpl.class);
bind(CreditCardProcessor.class).annotatedWith(Names.named("Checkout")).to(CheckoutCreditCardProcessor.class);
// 1.注入
@Inject
public List<NamedService> getAllItemServices(@Named("impl1") NamedService nameService1,@Named("impl2") NamedService nameService2) {
}
// 2.绑定
bind(NamedService.class).annotatedWith(Names.named("impl1")).to(NamedServiceImpl1.class);
bind(NamedService.class).annotatedWith(Names.named("impl2")).to(NamedServiceImpl2.class);

③ toInstance 实例绑定

bind(String.class).annotatedWith(Names.named("JDBC URL")).toInstance("jdbc:mysql://localhost/pizza");

④ @Provides 方法

public class BillingModule extends AbstractModule {@Overrideprotected void configure() {...}@ProvidesTransactionLog provideTransactionLog() {DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");transactionLog.setThreadPoolSize(30);return transactionLog;}
}

3. 作用域

Guice 提供了很多作用域,有单例 Singleton,Session 作用域 SessionScoped,Request 请求作用域 RequestScoped 等等。

默认情况下 Guice 会在每次注入的时候创建一个新对象,用以下方式设置作用域:

① 实现类上添加 @Singleton 注解

@Singleton
public class InMemoryTransactionLog implements TransactionLog {/* everything here should be threadsafe! */
}

② 在配置类中指定

bind(TranLog.class).to(TranLogImpl.class).in(Singleton.class);

③ 在 @Provides 方法中也中指定单例

@Provides @Singleton
TransactionLog provideTransactionLog() {...
}

4. 基本使用

① 引入依赖

<dependency><groupId>com.google.inject</groupId><artifactId>guice</artifactId><version>4.1.0</version>
</dependency>

② 业务接口 和 接口实现

public interface UserService {void process();
}public class UserServiceImpl implements UserService {@Overridepublic void process() {System.out.println("我需要做一些业务逻辑");}
}

③ 注入

public interface Application {void work();
}public class MyApp implements Application {private UserService userService;@Injectpublic MyApp(UserService userService) {this.userService = userService;}@Overridepublic void work() {userService.process();}
}

④ 依赖绑定

public class MyAppModule extends AbstractModule {@Overrideprotected void configure() {bind(UserService.class).to(UserServiceImpl.class);bind(Application.class).to(MyApp.class);}
}

⑤ 创建注入器 Guice.createInjector

public class MyAppTest {private static Injector injector;@BeforeClasspublic static void init() {injector = Guice.createInjector(new MyAppModule());}@Testpublic void testMyApp() {Application myApp = injector.getInstance(Application.class);myApp.work();}
}

参考1:JAVA轻量级IOC框架Guice - Leejk - 博客园

参考2:Guice 快速入门 - 腾讯云开发者社区-腾讯云

guice 官网地址:GitHub - google/guice: Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 8 and above, brought to you by Google.

二、Jersey

Jersey 是一个 REST 框架,官网地址:Eclipse Jersey

基于 Jersey 的 REST 应用,可以运行在 Servlet 环境下(例如 Tomcat),也可以脱离 Servlet 环境,使用内置容器(例如 Jetty)。

注意:

jersey 1.X 使用的是 sun 的 com.sun.jersey

jersey 2.X 使用的是 glassfish 的 org.glassfish.jersey

使用内置容器为例(使用Jetty发布Jersey服务)

jersey 1.X

项目结构:

① 添加 maven 依赖

<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-server</artifactId><version>9.3.8.v20160314</version>
</dependency><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-servlet</artifactId><version>9.3.8.v20160314</version>
</dependency><dependency><groupId>com.sun.jersey</groupId><artifactId>jersey-server</artifactId><version>1.19.1</version>
</dependency><dependency><groupId>com.sun.jersey</groupId><artifactId>jersey-servlet</artifactId><version>1.19.1</version>
</dependency>

② 创建一个 JettyServer 类,用于配置 Jetty 环境:

package com.yuyu.jersey;public class JettyServer {private void start() throws Exception {Server server = new Server(8080);ServletContextHandler context =new ServletContextHandler(ServletContextHandler.SESSIONS);context.setContextPath("/");server.setHandler(context);ServletHolder sh = new ServletHolder(ServletContainer.class);sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass","com.sun.jersey.api.core.PackagesResourceConfig");sh.setInitParameter("com.sun.jersey.config.property.packages","com.yuyu.jersey.api");context.addServlet(sh, "/*");server.start();}public void stop() throws Exception {}public static void main(String[] args) throws Exception {JettyServer server = new JettyServer();server.start();}
}

③ REST 服务的类(也称资源类,路径要和上面配置的保持一致)

package com.yuyu.jersey.api;@Path("/welcome")
public class WelcomeResource {@GET@Produces(MediaType.TEXT_PLAIN)public String sayHello() {return "Welcome to Jersey world";}
}

执行 main 方法,请求 http://localhost:8080/welcome,得到响应:



jersey 2.X

项目结构:

① 添加 maven 依赖

<dependency><groupId>org.glassfish.jersey.containers</groupId><artifactId>jersey-container-jetty-http</artifactId><version>2.21</version>
</dependency>

② 创建一个 Application 类,用于设置发布环境:

package com.yuyu.jersey;public class RestApplication extends ResourceConfig {public RestApplication(){this.packages("com.yuyu.jersey");}
}

· ResourceConfig 类继承了 Application 类,此类是 Jersey 中的基础类,用于定义一个 JAX-RS 应用的基础组件。

· 在 RestApplication 类的构造方法中,我们调用了 packages 方法注册了扫描资源类的基础包。


③ REST 服务的类(也称资源类)

package com.yuyu.jersey.test.demo;@Path("hello")
public class HelloService {@GET@Produces(MediaType.TEXT_PLAIN)public String hi(){return "hello jersey";}
}

1. 在类上面添加了 @Path("hello"),代表资源根路径为 hello;

2. @GET 代表该方法接受 GET类型请求;

3. @Produces 代表该方法的响应类型为 text/plain;

4. 该方法返回 String,这个 String 值 Jersey 会自动按照 text/plain 格式输出。


④ 发布应用

package com.yuyu.jersey;public class App {public static void main(String[] args) {JettyHttpContainerFactory.createServer(URI.create("http://localhost:8082/"), new RestApplication());}
}

执行 main 方法,请求 localhost:8082/hello,得到响应:

参考1:Jersey 开发RESTful(七)Jersey快速入门 - 简书

参考2:Jersey 开发RESTful(八)Jersey参数绑定 - 简书

参考3:Jetty + Jersey简单RESTful例子_飞飞好奇的博客-CSDN博客

jersey 官网:Eclipse Jersey

三、Jetty

Jetty 是一个开源的 servlet 容器,可以为JSP和Servlet提供运行时环境。

jetty 与 tomcat 区别:

(1) Jetty 比 Tomcat 架构更加简单。 jetty的所有组件都是基于 Handler 来实现,它的主要功能扩展都可以用 Handler 来实现。

(2) jetty 比较容易扩展第三方框架,所以也跟容易定制

(3) jetty更加轻量可以节省内存;

(4) tomcat 更加稳定、更加成熟。

参考:jetty、jetty原理、jetty与tomcat区别 - 知乎

四、Guice + Jersey + Jetty Demo

项目结构:

① 添加 maven 依赖

<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-server</artifactId><version>9.3.24.v20180605</version>
</dependency>
<dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-servlet</artifactId><version>9.3.24.v20180605</version>
</dependency><dependency><groupId>com.google.inject.extensions</groupId><artifactId>guice-servlet</artifactId><version>4.2.3</version>
</dependency>
<dependency><groupId>com.google.inject</groupId><artifactId>guice</artifactId><version>4.2.3</version>
</dependency><dependency><groupId>com.sun.jersey</groupId><artifactId>jersey-server</artifactId><version>1.19</version>
</dependency>
<dependency><groupId>com.sun.jersey.contribs</groupId><artifactId>jersey-guice</artifactId><version>1.19</version>
</dependency>

② 创建一个资源 api 服务

@Path("/myTest")
public class ResourceTest {@GET@Path("/test")@Produces(MediaType.TEXT_PLAIN)public String testApi(){return "this is a test";}
}

③ 创建 WebServer 配置 servlet

public class WebServer {private final Server jetty;private final Connector connector;@Injectpublic WebServer(Server jetty, Connector connector) {this.jetty = jetty;this.connector = connector;}public void start() throws Exception {this.jetty.addConnector(connector);ServletHolder apiServletHolder = new ServletHolder(new GuiceContainer(Start.getInjector()));apiServletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");apiServletHolder.setInitParameter("com.sun.jersey.config.property.packages", "com.yuyu.demo.api");ServletContextHandler context = new ServletContextHandler();context.setContextPath("/");context.addServlet(apiServletHolder, "/*");this.jetty.setHandler(context);this.jetty.start();}public void stop() throws Exception {this.jetty.stop();}
}

④ 实现 ConnectorProvider 为 jetty 提供 http 连接

public class HttpConnectorProvider implements Provider<Connector> {private Server jetty;@Injectpublic HttpConnectorProvider(Server jetty) {this.jetty = jetty;}@Overridepublic Connector get() {ServerConnector ret = new ServerConnector(this.jetty);ret.setName("test");ret.setHost("0.0.0.0");ret.setPort(8089);return ret;}
}

⑤ 创建 WebServerModule 绑定依赖

public class WebServerModule extends AbstractModule {private Server jetty;public WebServerModule() throws Exception {this.jetty = new Server();}@Overrideprotected void configure() {bind(Server.class).in(Scopes.SINGLETON);bind(WebServer.class).in(Scopes.SINGLETON);bind(Connector.class).toProvider(HttpConnectorProvider.class);}
}

⑥ 创建 main 方法执行服务

public class Start {private static Injector injector;public static void main(String[] args) throws Exception {injector = Guice.createInjector(new WebServerModule());WebServer webServer = injector.getInstance(WebServer.class);webServer.start();}public static Injector getInjector() {return injector;}
}

执行结果:

参考:GitHub - sunnygleason/j4-minimal: Minimal web application example using Embedded Jetty, Jersey, Guice, and Jackson

Guice + Jersey + Jetty 框架 - 学习笔记相关推荐

  1. Java日志框架学习笔记

    Java日志框架学习笔记 文章目录 0 主流Java日志框架 1 log4j 1.1 理论知识 1.1.1 Loggers日志记录器 1.1.2 Appenders输出端 1.1.3 Layout日志 ...

  2. SpringMVC框架--学习笔记(下)

    接上篇:SpirngMVC框架--学习笔记(上):https://blog.csdn.net/a745233700/article/details/81038382 17.全局异常处理: 系统中异常包 ...

  3. SpringMVC框架--学习笔记(上)

    1.SpringMVC入门程序: (1)导入jar包:spring核心jar包.spring-webmvc整合Jar包 (2)配置前端控制器:web.xml文件中 <?xml version=& ...

  4. mybatis框架--学习笔记(下)

    上篇:mybatis框架--学习笔记(上):https://blog.csdn.net/a745233700/article/details/81034021 8.高级映射: (1)一对一查询: ①使 ...

  5. mybatis框架--学习笔记(上)

    使用JDBC操作数据库的问题总结: (1)数据库连接,使用时创建,不使用时立即释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费,影响数据库性能. 设想:使用数据库连接池管理数据库连接. (2) ...

  6. JavaSE中Map框架学习笔记

    前言:最近几天都在生病,退烧之后身体虚弱.头疼.在床上躺了几天,什么事情都干不了.接下来这段时间,要好好加快进度才好. 前面用了三篇文章的篇幅学习了Collection框架的相关内容,而Map框架相对 ...

  7. python表单提交的两种方式_Flask框架学习笔记之表单基础介绍与表单提交方式

    本文实例讲述了Flask框架学习笔记之表单基础介绍与表单提交方式.分享给大家供大家参考,具体如下: 表单介绍 表单是HTML页面中负责数据采集功能的部件.由表单标签,表单域和表单按钮组成.通过表单,将 ...

  8. php框架费尔康,GitHub - majixian/study-phalcon: phalcon(费尔康)框架学习笔记

    phalcon(费尔康)框架学习笔记 以实例程序invo为例(invo程序放在网站根目录下的invo文件夹里,推荐php版本>=5.4) 环境不支持伪静态网址时的配置 第一步: 在app\con ...

  9. [Spring+SpringMVC+Mybatis]框架学习笔记(四):Spring实现AOP

    上一章:[Spring+SpringMVC+Mybatis]框架学习笔记(三):Spring实现JDBC 下一章:[Spring+SpringMVC+Mybatis]框架学习笔记(五):SpringA ...

最新文章

  1. Spring 中的 context
  2. 卓瑞机器人_校企合作专业共建记涪陵职教中心机器人专业中泰学术交流活动
  3. php 数学函数bc的使用(浮点数计算)
  4. 一些设计思想的汇集(2)
  5. 基于linux的MsQUIC编译及样例运行
  6. 华为云数据库GaussDB(for Cassandra)揭秘第二期:内存异常增长的排查经历
  7. kubernetes权威指南_如何快速上手成为大厂标配的kubernetes?
  8. 模块dll加载失败请确保该二进制_Windows漏洞利用开发 – 第3部分:偏移更改和重定位模块...
  9. java list 泛型 转换_Java中List与数组互相转换
  10. 多渠道归因分析(Attribution):python实现Shapley Value(四)
  11. android svg 线条动画教程,SVG 实现复杂线条动画
  12. 第十四章 - 垃圾回收概述
  13. 英特尔530和535哪个好_2020年终好物推荐,英特尔Evo平台认证更出彩
  14. SSM框架二手车交易网站源码+论文
  15. Error handling response: TypeError: Cannot read property ‘1‘ of null
  16. 【面试流水账】一年半经验前端年底求职路
  17. 【C++】逆序函数reverse()
  18. 消费者心理学:三个趣味经济学原理
  19. 一个LOGO背景的制作方法
  20. 为什么Quora选择用Python语言?

热门文章

  1. java rhino 运行 js_Rhino -- 基于java的javascript实现
  2. python酷q机器人_python qq机器人开发 利用Python读取QQ消息
  3. 优秀课件笔记之决策支持系统
  4. 推动长三角信创产业发展 华云数据承办的“十四五”规划系列座谈会信创专场顺利召开
  5. Exchange笔记之Exchange2010部署实施
  6. 微信小程序开发之全屏显示
  7. 某网友惊现言论:程序员没有技术壁垒,不值得拿高薪!网友:搞笑!
  8. C语言经典红白机坦克大战
  9. 实战:批量重启物理机或批量从pxe启动-ipmi命令(测试成功-工作实战)-2021.11.16
  10. 如何用vue做一个二级联动