使用自定义xml bean设置属性后,Spring Boot REST Controller无法正常工作

时间:2015-02-01 14:21:04

标签: java xml spring rest spring-boot

我正在学习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>

在访问/ first / test后的Before版本中,它返回OK,现在我在日志文件中出现空白页和Ambiguous mapping found错误。

有人可以向我解释如何将Spring Boot自动配置与自定义bean相结合吗?

1 个答案:

答案 0 :(得分:0)

  1. 如果可能,我还建议使用属性文件外部化配置。
  2. 编辑:Spring引导提供了关于topic的精美文档。

    1. 问题可能是XML配置和默认组件扫描的组合 - 可以定义两次相同的bean。如果是这种情况,请考虑&#34;手册&#34;通过http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html#excludeFilters--
    2. 排除