I am creating a multi-module project in a spring boot application and have an internal library which is created for all the common services,repository etc.
Then I have added this internal library as a dependency to the parent project .
#EnableDiscoveryClient
#SpringBootApplication
#ComponentScan({"com.testlab.internal"})
public class ProfileServiceApplication {
#LoadBalanced
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ProfileServiceApplication.class , args);
}
}
Now after this change all the controller mapping stopped working, i.e
spring is not able find the handle method for any mapping .
But after adding a test controller in the ProfileServiceApplication class it worked seamlessly .
#EnableDiscoveryClient
#SpringBootApplication
#ComponentScan({"com.testlab.internal"})
public class ProfileServiceApplication {
#LoadBalanced
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ProfileServiceApplication.class , args);
}
#GetMapping("/")
public String home() {
return "hello";
}
}
This is working.
And my controller looks like this.
#Slf4j
#RestController
#RequestMapping
public class PringConversationController {
#GetMapping("/test")
public String home() {
return "hello";
}
}
Thanks for any help in advance
Related
It's possible to mock response FeignClient via MockRestServiceServer(restTemplate)?
This example dosn't work:
Application.class
#SpringBootApplication
#EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
TicketService.class
#FeignClient("ws")
public interface TicketService {
#RequestMapping(value = "/tickets/")
List<Ticket> findAllTickets();
}
TestConfig.class
#Profile("test")
#Configuration
public class TestConfig {
#Bean
#Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
MyTest.class
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {Application.class}, properties = {"ws.ribbon.listOfServers:example.com"})
public class MyTest {
#Autowired
RestTemplate restTemplate;
#Autowired
DispatcherService dispatcherService; // service where the execution of the method TicketService.findAllTickets();
private MockRestServiceServer mockServer;
#Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
#Test
public void ticket() {
mockServer.expect(requestTo("http://example.com/tickets/"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(new ClassPathResource("tickets.json"), MediaType.APPLICATION_JSON));
dispatcherService.run();
}
}
But going a request to the real server example.com.
At the moment I know 2 good approaches:
Use wiremock library (for Spring Boot i use spring-cloud-contract-wiremock)
Mockito (i use #MockBean)
I have a #RestController where one of the arguments of a controller method is Locale
#RequestMapping("/{id}")
public Survey getSurvey( #PathVariable("id") SurveyId surveyId,
Locale locale ) { ... }
I have a working integration test (using RestAssured) where I can switch locale by setting the Accept-Language header.
I now want to document this using Spring REST docs as well. Setting the header in this case (using MockMvc) does not work.
My test something like this:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration
#WebAppConfiguration
public void SurveyControllerDocumentation {
// Test methods here
...
// Application context for documentation test
#Configuration
#EnableAutoConfiguration
public static class TestConfiguration {
#Bean
public SurveyController controller(MessageSource messageSource) {
return new SurveyController(userService(), messageSource, surveyService());
}
#Bean
public UserService userService() {
return mock(UserService.class);
}
#Bean
public SurveyService surveyService() {
return mock(SurveyService.class);
}
#Bean
public CustomEditorsControllerAdvice customEditorsControllerAdvice() {
return new CustomEditorsControllerAdvice();
}
#Bean
public RestResponseEntityExceptionHandler exceptionHandler() {
return new RestResponseEntityExceptionHandler();
}
}
}
Is there some bean that I need to explicitly add to my test context that does the locale injection?
I am using Spring Boot 1.3.3 (which has Spring 4.2.5)
You can set the Locale using the locale(Locale) method on the request builder:
mockMvc.perform(
get("/")
.accept(MediaType.APPLICATION_JSON)
.locale(Locale.GERMAN))
.andExpect(status().isOk())
.andDo(document("example"));
Can somebody tell me how to configure #RestController?
I do this :
#RestController
#EnableAutoConfiguration
public class Application {
#RequestMapping("/test.htm")
#ResponseBody
String home() {
return "Hello Worlds!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
#Controller
public class MusicControler {
class Test{
String name;
int age;
}
#RequestMapping(value = "/MyController")
public Test MyController() {
Test test = new Test();
test.name = "zl.shi";
test.age = 16;
return test;
}
}
When I request /test.htm, it is ok but I get response 404 for /testController.htm. Can someone help me about it?
use following code to create rest controller
#RestController
#RequestMapping("/service/")
public class Application {
#RequestMapping(value = "/getmemberdetail/{id}/{info}", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<String> getuserdetail(#PathVariable int portalType,#PathVariable("id") int id,#PathVariable("info") String info) throws JsonProcessingException, ParseException{}
}
if you want to know how to use it you should read about it
Difference between spring #Controller and #RestController annotation
when you make starter-project spring you should make another class where you are going to put you controller don't forget RestController annotation or the controller annotation ( as best practice you shouldn't use the starter class of spring boot ) i hope this helps you
ps don't tag spring-mvc and spring-boot it's not the same thing
I am implementing rest services with Spring Boot. The entity classes are defined in a separate package. So I added that with Component annotation in Application.java.
#Configuration
#EnableAutoConfiguration
#ComponentScan("org.mdacc.rists.cghub.model")
#EnableJpaRepositories(basePackages = "org.mdacc.rists.cghub.model")
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
}
Here is my controller class:
// SeqController.java
#RestController
public class SeqController {
#Autowired
private SeqService seqService;
#RequestMapping(
value = "/api/seqs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<SeqTb>> getSeqs() {
List<SeqTb> seqs = seqService.findAll();
return new ResponseEntity<List<SeqTb>>(seqs, HttpStatus.OK);
}
}
I also created a JPA data repository that extends JPARepository in which I added custom query code.
// SeqRepository.java
#Repository
public interface SeqRepository extends JpaRepository<SeqTb, Integer> {
#Override
public List<SeqTb> findAll();
#Query("SELECT s FROM SeqTb s where s.analysisId = :analysisId")
public SeqTb findByAnalysisId(String analysisId);
}
Below is the servicebean class that implements a service interface
// SeqServiceBean.java
#Service
public class SeqServiceBean implements SeqService {
#Autowired
private SeqRepository seqRepository;
#Override
public List<SeqTb> findAll() {
List<SeqTb> seqs = seqRepository.findAll();
return seqs;
}
public SeqTb findByAnalysisId(String analysisId) {
SeqTb seq = seqRepository.findByAnalysisId(analysisId);
return seq;
}
}
When I started the application and type the following url in the browser "http://localhost:8080/api/seqs" , I got 404 error. What did I miss?
Edit #1:
I decided to take out the JPA repository stuff and change the controller class to the following:
#RestController
//#RequestMapping("/")
public class SeqController {
private static BigInteger nextId;
private static Map<BigInteger, Greeting> greetingMap;
private static Greeting save(Greeting greeting) {
if(greetingMap == null) {
greetingMap = new HashMap<BigInteger, Greeting>();
nextId = BigInteger.ONE;
}
greeting.setId(nextId);
nextId = nextId.add(BigInteger.ONE);
greetingMap.put(greeting.getId(), greeting);
return greeting;
}
static {
Greeting g1 = new Greeting();
g1.setText("Hello World!");
save(g1);
Greeting g2 = new Greeting();
g1.setText("Hola Mundo!");
save(g2);
}
#RequestMapping(
value = "/api/greetings",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Greeting>> getGreetings() {
Collection<Greeting> greetings = greetingMap.values();
return new ResponseEntity<Collection<Greeting>>(greetings, HttpStatus.OK);
}
}
When I started the application and put "localhost:8080/api/greetings" in my browser I still got 404.
==>Did you make sure that your Spring Boot application class and your Rest Controller are in the same base package? For Example if your package for Spring Boot application class is com.example.demo, then your Rest Controller should be in same base package as com.example.demo.controller.
==>I think that is the reason boot is unable to map to the uri of your rest controller. Because #SpringBootApplication has #ComponentScan and #Configuration embedded in it already. Try doing this. I hope it works.
If spring boot starter web is not there in your pom.xml then add the same as the reason could be the code not being able to map the endpoints.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The first thing I would try is to put #RequestMapping("/") on the class definition of the controller. Keep the same value on the method.
Another thing, unrelated to your problem, is that you do not need to define that custom query. JPA is actually smart enough to do the query you defined just by using that method name. Check out the findByLastName example here: https://spring.io/guides/gs/accessing-data-jpa/.
I have a application that uses Spring cloud config (--spring.profiles.active=native) and also serves up some html pages within the same application. All is fine until I introduce static resources (src/main/resources/css/bootstrap-switch.css). The URL calls to http://localhost:8080/css/bootstrap-switch.css fails with this Exception:
{"timestamp":1438114326940,"status":406,"error":"Not Acceptable","exception":"org.springframework.web.HttpMediaTypeNotAcceptableException","message":"Could not find acceptable representation","path":"/css/bootstrap-switch.css"}
When I disable the #EnableConfigServer, the URL returns the CSS content. I am on Spring Cloud Config version 1.0.2.
Here's my minimalist code that can reproduce this issue:
#SpringBootApplication
#EnableConfigServer
public class Application {
public static void main(String args[]) {
SpringApplication.run(ApplicationConfiguration.class, args);
}
}
#Configuration
#SpringBootApplication
class ApplicationConfiguration {
#Bean
public TestController testController() {
return new TestController();
}
#Bean
public MvcController mvcController() {
return new MvcController();
}
}
#RestController
class TestController {
#RequestMapping("/test")
#ResponseBody
public String test() {
return "hello world";
}
}
#Controller
class MvcController {
#RequestMapping("/landing")
public String landingPage() {
return "landing";
}
}
Config server by default has an api that matches /*/*. You can move the root of the api by changing spring.cloud.config.server.prefix=myroot.