I'm trying to create a simple REST service with JAX-RS (Jersey), without using Spring. I want to have the typical structure of: Resource, that use a Service (typical interface with method findById
, findAll...), and that Service injected in the Resource.
It seems that CDI automatically scans beans and injects them (having a empty beans.xml
in the project) but... it doesn't work for me.
This is my Resource class:
@Path("users")
@ManagedBean
public class UserController {
@Inject
private UserService userService;
@GET()
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") Long id) {
return userService.findById(id);
}
}
And this is my Service and its impl class (it´s a mock...):
public interface UserService {
User findById(Long id);
List<User> findAll();
User save(User user);
User update(User user);
void delete(Long id);
}
public class UserServiceMock implements UserService {
// omitted constants
@Override
public User findById(Long id) {
return new User()
.setId(id)
.setName(NAME_GANDALF)
.setPhone(PHONE_666554433)
.setType(TYPE_1)
.setBirthDate(LocalDate.parse(STRING_DATE_19110102));
}
@Override
public List<User> findAll() {
return Arrays.asList(
new User()
.setId(USER_ID_12)
.setName(NAME_GANDALF)
.setPhone(PHONE_666554433)
.setType(TYPE_1)
.setBirthDate(LocalDate.parse(STRING_DATE_19110102)),
new User()
.setId(USER_ID_140)
.setName(NAME_ARAGORN)
.setPhone(PHONE_661534411)
.setType(TYPE_1)
.setBirthDate(LocalDate.parse(STRING_DATE_19230716)),
new User()
.setId(USER_ID_453321)
.setName(NAME_FRODO)
.setPhone(PHONE_666222211)
.setType(TYPE_2)
.setBirthDate(LocalDate.parse(STRING_DATE_19511124))
);
}
@Override
public User save(User user) {
return user.setId(USER_ID_453321);
}
@Override
public User update(User user) {
return user;
}
@Override
public void delete(Long id) {
// delete user by id
}
}
And I'm using a "no web.xml" configuration, with this class:
@ApplicationPath("api")
public class RestApplication extends ResourceConfig {
}
The only workaround I found is to "register" the service in the RestApplication class:
@ApplicationPath("api")
public class RestApplication extends ResourceConfig {
public RestApplication() {
register(UserController.class);
register(new AbstractBinder() {
@Override
protected void configure() {
bind(new UserServiceMock()).to(UserService.class);
}
});
}
}
Is there another solution to this problem? I'd rather not to register all my services and other stuff in this class manually...
I tried with annotations like @Default
, @Qualifier
and more (in the service), and no one works...