I'm using SpringBoot 2.2.6 and I want to know if is it possibile to Inject a DTO inside my Controller. It is a DTO with info coming from various entities..
For example I have a service that build this DTO:
#Service
public class SomeService() {
public ThisDTO getThisDTO() {
Entity entity = repository.findBySome();
return transformToDto(entity);
}
}
Now suppose I have a Controller like this:
#RestController
#RequestMapping(value = "/api/v1/Test")
public void TestController {
}
I would like to use ThisDTO in all method of above Controller but I don't want to do something like:
#RestController
#RequestMapping(value = "/api/v1/Test")
public void TestController {
#Autowired
SomeService someService;
#GetMapping
public void method1() {
ThisDTO thisDTO = someService.getThisDTO();
}
#GetMapping
public void method2() {
ThisDTO thisDTO = someService.getThisDTO();
}
...
...
}
but I would like to know if there's a way to do something like:
#RestController
#RequestMapping(value = "/api/v1/Test")
public void TestController {
#Inject // or something else
ThisDTO thisDto;
...
...
}
Thank you all!
Related
In Jersey we can do something like
#Path("/")
public class TopResource{
#GET
public Response getTop() { ... }
#Path("content")
public ContentResource getContentResource() {
return new ContentResource();
}
}
public class ContentResource {
#GET
public Response getContent() { ... }
}
so,
https://<host> will invoke getTop()
https://<host>/content will invoke getContent()
is there any equivalent in Spring?
I tried
#RestController
#RequestMapping("/")
public class TopResource{
#GetMapping()
public Response getTop() { ... }
#RequestMapping("content")
public ContentResource getContentResource() {
return new ContentResource();
}
}
#RestController
public class ContentResource {
#GetMapping()
public Response getContent() { ... }
}
only top resource works. content would return 404 Not Found.
Not sure how to do this in Spring Boot.
Tried replacing #RestController with #Resource and #Controller for content, but still got 404 Not Found.
There is no option to retun a whole class, please use the Annotation #RequestMapping on top of your content class to split them up.
#RestController
#RequestMapping("/")
public class TopResource{
#GetMapping()
public Response getTop() { ... }
}
#RestController
#RequestMapping("content")
public class ContentResource {
#GetMapping()
public Response getContent() { ... }
}
Here is a dummy project for the same :-
BlogApplication.java
#SpringBootApplication
#RestController
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
HtmlController.java
#Controller //does not work
OR
#RestController //works
public class HtmlController {
#GetMapping("/getHtmlFile")
public String getHtmlFile() {
return "Bit Torrent Brief";
}
}
Why is it that #RestController is able to map getHtmlFile but #Controller returns 404 when /getHtmlFile is hit?
#RestController is the combination of #Controller and #ResponseBody.
when you use #Controller, you should write #ResponseBody before your method return type
#Controller
public class HtmlController {
#GetMapping("/getHtmlFile")
public #ResponseBody String getHtmlFile() {
return "Bit Torrent Brief";
}
}
This works.
I have Enum Class. I Need to send a Enum class Response from the Spring controller.
I am not able understand how to sent class as Response in spring controller. Please help me for that.
You can add anything which Jackson can de-serialize in a reponse
#RestController
public class HelloController {
#RequestMapping("/monday")
public ResponseEntity<DayOfWeek> monday() {
return new ResponseEntity<DayOfWeek>(DayOfWeek.MONDAY, HttpStatus.OK);
}
#RequestMapping("/days")
public ResponseEntity<List<DayOfWeek>> days() {
return new ResponseEntity<List<DayOfWeek>>(Arrays.asList(DayOfWeek.values()), HttpStatus.OK);
}
}
You can prove this to yourself with the following test, just do the Jacskon de-serialization manually
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class HelloControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void monday() throws Exception {
String json = new ObjectMapper().writeValueAsString(DayOfWeek.MONDAY);
mvc.perform(MockMvcRequestBuilders.get("/monday").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(content().string(equalTo(json)));
}
#Test
public void days() throws Exception {
String json = new ObjectMapper().writeValueAsString(Arrays.asList(DayOfWeek.values()));
mvc.perform(MockMvcRequestBuilders.get("/days").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(content().string(equalTo(json)));
}
}
If you wanna return all enum values than try something like this:
#GetMapping("enum")
public List<MyEnum> paymentMethods() {
return Arrays.asList(MyEnum.values());
}
public enum MyEnum {
FIRST, SECOND, THIRD;
}
Take the following general abstract class:
#Configurable
public abstract class TestEntityRoot {
public abstract String print();
}
And a subclass:
#Configurable
public class TestEntity extends TestEntityRoot{
private TestEntityService testEntityService;
#Autowired
public void setTestEntityService(TestEntityService testEntityService) {
this.testEntityService = testEntityService;
}
#Override
public String print() {
return testEntityService.print();
}
}
When call controller:
#RestController
public class TestEntityController {
#GetMapping(name = "/test")
public String print() {
TestEntity entity = new TestEntity();
return entity.print();
}
}
everything ok. But if call like this:
#RestController
public class TestEntityController {
#GetMapping(name = "/test")
public String print() {
TestEntityRoot entity = new TestEntity();
return entity.print();
}
}
i get null pointer. Is it possible that second example work?
In the second case you create manually the class rather than using spring's bean. Autowire the bean instead. See
#RestController
public class TestEntityController {
#Autowired
private TestEntity entity
#GetMapping(name = "/test")
public String print() {
return entity.print();
}
}
I have an abstract class
I try to have all generic method in this class.
I get issue about mapping.
public abstract class BaseControllerNew<T extends BaseEntity, R extends BaseDto, S extends BaseSearch> {
...
#GetMapping(value = "/{id}")
public R getById(#PathVariable("id") Integer id){
return baseServiceNew.getById(id);
}
#GetMapping(value = "/")
public Page<R> get(Pageable page){
return baseServiceNew.get(page);
}
....
}
#RequestMapping(value = "/rest/vehicules")
#RestController
public class VehiculesRestController extends BaseControllerNew<Vehicules, VehiculesDto, VehiculesSearch>{
private VehiculesServiceImpl vehiculesService;
#Autowired
public VehiculesRestController(final VehiculesServiceImpl vehiculesService) {
super(vehiculesService);
this.vehiculesService = vehiculesService;
}
I'm able to call
/rest/vehicules/1
but i get 404 for
/rest/vehicules
The problem is with your additional "/", this means your URL will be "/rest/vehicules/"
You only need #GetMapping
#GetMapping
public Page<R> get(Pageable page){
return baseServiceNew.get(page);
}