我正在学习 Spring 框架(更普遍的是 Java EE)。
我喜欢使用 xml 文件传递配置的功能。我从this开始示例,效果很好。
唯一的问题是,一旦我使用 beans 添加自定义 xml 配置来设置 Controller 内的属性值,它就不再工作了,在服务器日志文件中它显示 Caused by: java.lang.IllegalStateException: 发现不明确的映射。无法映射 'com.example.controller.FirstController#0' bean 方法 (...)
然后它会列出 Controller 中的所有方法,就像我使用相同的 RequestMapping 定义多个方法一样(事实并非如此)。
我想设置一个属性,但似乎因此整个自动配置不再起作用。
之前
主类
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
Controller 类
@RestController
@RequestMapping("first")
public class FirstController {
protected final Logger log = LoggerFactory.getLogger(getClass());
@RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
}
}
之后
主类
@Configuration
@ComponentScan
@EnableAutoConfiguration
@ImportResource("classpath:config.xml")
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
Controller 类
@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 文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- test bean -->
<bean class="com.example.controller.FirstController">
<property name="testingbean" value="works"/>
</bean>
</beans>
在 Before
版本中,访问/first/test 后返回 OK
,现在我在日志文件中收到空白页面和 发现模糊映射
错误。
有人可以向我解释如何将 Spring Boot 自动配置与自定义定义的 bean 混合使用吗?
最佳答案
- 如果可能的话,我还建议使用属性文件来外部化配置。
编辑:Spring boot 提供了相关的详细文档 topic .
- 问题可能是 XML 配置和默认组件扫描的组合 - 相同的 bean 可以定义两次。如果是这种情况,请考虑通过 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html#excludeFilters-- 进行“手动”排除
关于java - 使用自定义 xml bean 设置属性后,Spring Boot REST Controller 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263695/