【发布时间】:2015-03-31 13:40:52
【问题描述】:
我正在学习 Spring 框架(更普遍的是 Java EE)。
我喜欢使用 xml 文件传递配置的特性。我从this 示例开始,它运行良好。
唯一的问题是,一旦我使用 bean 添加了我的自定义 xml 配置来设置控制器内部的属性值,它就不再起作用了,在服务器日志文件中它显示 Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'com.example.controller.FirstController#0' bean method (...) 然后它列出了控制器就像我用相同的 RequestMapping 定义了多个方法一样(事实并非如此)。
我想设置一个属性,但似乎因此整个自动配置不再起作用。
之前
主类
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
控制器类
@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);
}
}
控制器类
@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,现在我在日志文件中得到空白页和Ambiguous mapping found 错误。
有人可以向我解释如何将 Spring Boot 自动配置与自定义 bean 混合使用吗?
【问题讨论】:
-
你为什么使用 XML?只需在
@Configuration类中定义@Bean或在@CompomentScan位置定义@Component。顺便说一句,有一个新的@SpringBootApplication注释可以替代一些标准注释。 -
这样我可以从我存储在 ressources 目录等的文件中加载字符串吗? (这是我的目标,我知道怎么做,但只使用 xml 配置)我试图避免非常大的源文件,我的应用程序将使用很多字符串
-
我不明白。如果您需要加载属性文件,请使用
PropertySourcesPlaceholderConfigurer。如果您需要配置属性,请考虑使用externalized configuration。如果您需要 i18n,那么这完全是一个不同的问题。 -
AdminController长什么样子?? -
@BoristheSpider,假设我使用 .properties 文件将配置外部化,它是否提供与 xml beans 完全相同的功能?我问是因为对于 xml bean,我在 Internet 上有很多示例,但是对于属性没有那么多。
标签: java xml spring rest spring-boot