Autowired Class返回空值

时间:2017-10-15 13:52:36

标签: java spring

我实现了一个基于Spring的小服务。我想在DemoController中自动发送类Demo。因此,我在beans.xml文件中定义了它的值。似乎spring发现了bean,因为一切都在编译。但是服务的返回值如下所示:

  

{" valueUno":0," valueDue":空}

DemoApplication:

@SpringBootApplication
@ComponentScan({"com"})
@EnableAutoConfiguration
public class DemoApplication {

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

    }
}

演示:

@Component
public class Demo {

    private int valueUno;
    private String valueDue;
    //getter, setter....
}

DemoController:

@RestController
public class DemoController {

    @Autowired
    private Demo demo;

    @RequestMapping(
            value = "/welcome",
            method = RequestMethod.GET
            )   
    public HttpEntity<Demo> getMessage() {
        return new HttpEntity<Demo>(this.demo);
    }

}

beans.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">
    <bean id="demo" class="com.example.demo.Demo">
        <property name="valueUno" value="50"></property>
        <property name="valueDue" value="Hello"></property>
    </bean>
</beans>

一切都在一个包里面。我不明白......

2 个答案:

答案 0 :(得分:4)

您已将Demo注释为@Component。因此,Spring在组件扫描期间使用其默认构造函数实例化此类的bean(您已使用@ComponentScan({"com"})启用它),然后将其注入(自动装配)到DemoController。因此,自动装配的bean不是beans.xml中定义的那个。

有两种方法可以解决这个问题:

1)如果您想使用XML配置,请从@Component类中删除Demo,并将@ImportResource("classpath:beans.xml")注释添加到Controller类。

2)如果你想使用JavaConfig(注释),你需要像这样添加单独的类:

@Configuration
public class MyConfiguration {
    @Bean
    public Demo demo() {
        return new Demo(50, "Hello"); // or initialize using setters
    }
}

...并向您的Controller类添加@Import(MyConfiguration.class)注释,并从@Component类中删除Demo

答案 1 :(得分:2)

作为@PresentProgrammer所说的解决方案,您可以将XML配置移动到Java配置,如下所示:

    @Bean
    public Demo demo() {
        Demo demo = new Demo();
        demo.setValueUno(50);
        demo.setValueDue("Hello");
        return demo;
    }

您可以将此配置直接添加到DemoApplication类或配置类:

@Configuration
public class BeanConfiguration {

    //Bean Configurations

}

有关详细信息,请阅读Java-based container configuration Spring文档。

相关问题