繁体   English   中英

使用自定义xml bean设置属性后,Spring Boot REST Controller不起作用

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

我正在学习Spring框架(更一般地说是Java EE)。

我喜欢使用xml文件传递配置的功能。 我从这个例子开始,它运行良好。

唯一的问题是,一旦我添加了带有bean的自定义xml配置以在控制器内设置属性值,它就不再起作用,它在服务器日志文件中显示原因Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'com.example.controller.FirstController#0' bean method (...) 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. 如果可能,我还建议使用属性文件将配置外部化。

编辑:Spring boot提供了关于该主题的优质文档。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM