User Spring Framework.
https://projects.spring.io/spring-framework/
https://jersey.java.net/documentation/latest/spring.html
There a full working example here:
https://github.com/jersey/jersey/tree/2.22.2/examples/helloworld-spring-webapp
You basically add this dependency to your jersey project and it'll include Spring automatically:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${project.version}</version>
</dependency>
and then you define your Spring Beans in a file called applicationContext.xml and src/main/resources:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="mySingletonService" class="com.test.MyService"/>
<beans/>
Last But not least, in your actual resource you can inject this singleton service using the @Autowire annotation:
@Path("/resource")
@Component
public class MyResource {
@Autowired
private MyService myService;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getHello() {
return myService.sayHello();
}
}
Using the @SingletonResource and initializing state within the resource is a terrible, terrible idea IMO. Separation of concerns is important, and keeping state in a REST Resource is just plain awful. Separate the code that deals with your interface (REST) and your business logic by creating let's say an LDAPResource and an LDAPService. The part Spring plays here is just the wiring that otherwise you'd have to instantiate yourself.