简体   繁体   English

@Bean 注释在 Spring Boot 中不起作用

[英]@Bean annotation not working in Spring Boot

I created the Model我创建了模型

@Repository
public class Model {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Model(String name) {
        super();
        this.name = name;
    }

    public Model() {
        super();
        // TODO Auto-generated constructor stub
    }
}

Then I created the configuration class with a bean然后我用bean创建了配置类

@Component
public class Config {

    @Bean
    public Model beanB() {
        Model a=new Model();
        a.setName("Daniel3");
        return a;
    }   
}

Then I created the Controller class然后我创建了 Controller 类

@RestController
public class TestController {

    @Autowired
    Model model;

    @GetMapping("/test")
    @ResponseBody
    public Model test() {
        return model;
    }

}

When I hit the controller url, I am getting the below response当我点击控制器网址时,我收到以下响应

{"name":null}

But if I modify configuration class as但是如果我将配置类修改为

    @Bean
    @Primary
    public Model beanB() {
        Model a=new Model();
        a.setName("test");
        return a;
    }   

I get the output as {"name":"test"} .我得到的输出为{"name":"test"} And I am observing the same behaviour when using Autowired Model instead of new Model()当使用 Autowired Model 而不是 new Model() 时,我观察到相同的行为

Can anyone explain this behavior?谁能解释这种行为?

Right now, you are registering two different beans of type Model as you use @Repository on your Model class which you shouldn't do as this is used for database repositories.现在,当您在Model类上使用@Repository时,您正在注册两个不同的Model类型的 bean,您不应该这样做,因为它用于数据库存储库。 If you remove @Repository from your Model you'll only have one bean definition and hence get the correct one injected to your controller:如果您从Model删除@Repository ,您将只有一个 bean 定义,因此将正确的一个注入到您的控制器中:

// @Repository remove this, should not be used here
public class Model {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Model(String name) {
        super();
        this.name = name;
    }

    public Model() {
        super();
        // TODO Auto-generated constructor stub
    }
}

The reason it works with @Primary is that you then define are order hof importance among all beans of the type Model .它与@Primary一起使用的原因是您然后定义了Model类型的所有 bean 之间的重要性顺序。

@Repository意味着您在 bean 工厂中注入了一个类型为 repository 的 bean,此外,当您还添加@Bean注释时,它将成为第二个 bean,因此它在这两个 bean 之间创建了一个重要的问题,当您添加@Primary它赋予了重要性到你的@Bean注释 bean。

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

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