我正在使用Jersey创建REST API,但我不明白如何将依赖实例注入我的资源类,如我的两个示例类所示:
MyApplication.java
.left-column {
width: 35%;
margin-left: 20px;
margin-right: 50px;
float: left;
overflow: hidden;
}
.right-column {
overflow: hidden;
}
.intro-block {
background-color: #22AAA1;
margin: 0 auto;
/*max-width: 950px;*/
}
.bb {
background-color: red;
}
MyResource.java
<body>
<header>
<section class="intro-block">
<div class="left-column">
<img class="profile-pic right-column" src="img/11.jpg">
</div>
<div class="right-column">
<h1>lorem ipsum</h1>
<h4>lorem ipsum</h4>
</div>
</section>
</header>
<main>
<section class="bb">
<h3>lorem ipsum</h3>
<div class="left-column">
<div>
<p>lorem ipsum</p>
</div>
</div>
<div class="right-column">
<h5>lorem ipsum</h5>
</div>
</section>
</main>
当然,单例类可以保存数据,并且可以从资源内部获取数据,但是如果不使用单例,是不是更好的方法?我刚刚找到了关于如何注入类而不是像this
这样的实例的示例更新
我读了链接的线程,但我认为我的问题不同,因为我想从'MyApplication'中注入一个用参数实例化的实例。据我了解链接线程,它只解释了如何注入由public class MyApplication {
public static void main(String[] args) {
MyDataProvider dataProvider = new MyDataProvider(args); <---- Dependency
// ... boot
// Setting up REST API
ResourceConfig config = new ResourceConfig();
config.packages("org.foo.resources");
ServletHolder servlet = new ServletHolder(new ServletContainer(config));
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(server, "/*");
context.addServlet(servlet, "/*");
try {
server.start();
server.join();
} catch (InterruptedException e) {
} catch (Exception e) {
} finally {
server.destroy();
}
}
}
实例化的类实例。我错了吗?如果是,可以请某人解释如何注入已经实例化的'MyDataProvider'实例。
或更简短:
构造@Path("myresource")
public class MyResource {
private String name;
private String description;
@Context
HttpServletRequest request;
@Context
SecurityContext context;
@Inject
MyDataProvider dataProvider; <------ How to do this?
@GET
@Produces(MediaType.APPLICATION_JSON)
public MyResource myresource() {
name = dataProvider.loadSomeFancyStuff();
description = dataProvider.loadSomeAwesomeStuff();
}
}
的地方以及Jersey
如何知道应该在示例'basic-dependency-injection-using-jerseys'中注入哪个实例,我可能无法链接到?