Sunday, 1 February 2015

Spring Boot REST Controller doesn't work after setting attribute with custom xml bean



I am learning Spring framework (more generally J2EE).


I like the feature of passing the configuration using xml files. I started by the this example and it worked fine.


The only problem is that once I add my custom xml configuration with beans to set the attribute value inside the controller it doesn't work anymore, in the server log file it says Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'com.example.controller.FirstController#0' bean method (...) then it lists all the methods in the controller exactly like if I defined multiple methods with identical RequestMapping (which is not the case).


I wanted to set a single attribute, but it seems that because of that the entire autoconfiguration doesn't work anymore.


Before


Main class



@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MainApplication {

public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}


Controller class



@RestController
@RequestMapping("first")
public class FirstController {
protected final Logger log = LoggerFactory.getLogger(getClass());

@RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
}
}


After


Main class



@Configuration
@ComponentScan
@EnableAutoConfiguration
@ImportResource("classpath:config.xml")
public class MainApplication {

public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}


Controller class



@RestController
@RequestMapping("first")
public class FirstController {
protected final Logger log = LoggerFactory.getLogger(getClass());

private String testingbean;
public void setTestingbean(String testingbean) {
this.testingbean = testingbean;
}

@RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
}

@RequestMapping("beantest")
public String testBeans() {
return testingbean;
}
}


Config.xml file



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG">

<!-- test bean -->
<bean class="com.example.controller.AdminController">
<property name="testingbean" value="works"/>
</bean>
</beans>


In the Before version after accessing /first/test it returned OK, now I get blank page and Ambiguous mapping found error in the log file.


Could someone explain to me how to mix Spring Boot autoconfiguration with custom defined beans?


No comments:

Post a Comment